C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: We can use one constant to specify another constant. Here the "height" constant is based on the final width constant.
Java program that uses final on class
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());
}
}
Output
200
Here: We use a final static string. This is a constant that can be accessed on the type, not an instance of the type. It cannot be changed.
Java program that uses final static String
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);
}
}
Output
Hello world program
Java program that uses final String
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);
}
}
Output
Hyperion
true
false
Java program that uses final int
public class Program {
public static void main(String[] args) {
final int size = 10;
// This fails with a compilation error.
size = 200;
}
}
Output
The final local variable size cannot be assigned.
It must be blank and not using a compound assignment