final keyword in Java tutorial

“Success is never final, failure is never fatal. It’s courage that counts” John Wooden

The final keyword in Java

The value of a variable by default is changeable and any method that has the access to the variable can change its value.

But there are many times in programming where we want to create a variable and store a value into it only once and after that we don’t want the value to be changed.

So to make sure the value of a variable will never change after the first initialization, we can use the keyword final before the data type of a variable and that will turn the variable into constant.

For example:

public class Simple {

public static void main(String[] args){
final int age;
age = 100;
System.out.println(age);
}
}

Output: 100

Remember: we can only initialize a final variable only once. After that any attempt to reassign another value to a final variable will return compile time error.

Another example:

public class Simple {

public static void main(String[] args){
final int age;
age = 100;
age = 200;
System.out.println(age);
}
}

Output:

Error: variable age might already have been assigned

As you can see, because we tried to reassign the variable age we’ve got the compile time error.