A value cannot be changed. For example 10 is 10. We cannot change 10 to 20. With a variable, we can assign new values—but a value is final.
With the final keyword, we indicate a field or local is constant (a value). A final thing is in its terminal state. It cannot ever become something new.
Here we introduce a class
with 2 final ints on it. The Box class
has width and height final values on it. These can be accessed like fields.
class Box { // This class has final ints on it. final int width = 10; final int height = width * 2; public int area() { return width * height; } } public class Program { public static void main(String[] args) { // Create and use class with final ints. Box box = new Box(); System.out.println(box.area()); } }200
static
In Java the static
keyword means a field that is based on the type, not the instance of the type. It only exists once at a time in memory.
static
string
. This is a constant that can be accessed on the type, not an instance of the type. It cannot be changed.public class Program { // This String is both final and static. final static String description = "Hello world program"; public static void main(String[] args) { // Print string. System.out.println(description); } }Hello world program
String
Here we use a final String
. We then create a string
with the same value (Hyperion) and compare the two. We must use equals()
to compare two strings based on data.
public class Program { public static void main(String[] args) { // This is a final String. final String name = "Hyperion"; // Construct another String. String test = "Hyper"; String test2 = test + "ion"; System.out.println(name); // Equals test the two strings. System.out.println(name.equals(test2)); // The string references are different. System.out.println(name == test2); } }Hyperion true false
We cannot assign to a final value. We receive a "cannot be assigned" error in this case. The program will not compile.
public class Program { public static void main(String[] args) { final int size = 10; // This fails with a compilation error. size = 200; } }The final local variable size cannot be assigned. It must be blank and not using a compound assignment
The final keyword is not related to the finally keyword. Final indicates constancy. Meanwhile finally is part of an exception handling construct.