final Java
Introduction
The keyword final protects variables from changes.
final variables
Let us name the example file Main.java
public class Main {
final int x = 10;
public static void main(String[] args) {
Main myObj = new Main();
myObj.x = 7; // will generate an error
System.out.println(myObj.x);
}
}
javac -encoding utf8 Main.java
Main.java:6: error: cannot assign a value to final variable x myObj.x = 7; ^ 1 error
Article author: Andrei Olegovich