Final variable in Java


A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object. 

However, the data within the object can be changed. So, the state of the object can be changed but not the reference.

With variables, the final modifier often is used with static to make the constant a class variable.

Example

public class Test {
   final int value = 10;
   // The following are examples of declaring constants:
   public static final int BOXWIDTH = 6;
   static final String TITLE = "Manager";
   public void changeValue() {
      value = 12; // will give an error
   }
}

Updated on: 06-Feb-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements