final variables in Java



Final Variables

A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to an 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 Tester {
   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
   }
   public void displayValue(){
      System.out.println(value);
   }
   public static void main(String[] args) {

      Tester t = new Tester();
      t.changeValue();
      t.displayValue();
   }
}

Output

Compiler will throw an error during compilation.

Tester.java:9: error: cannot assign a value to final variable value
value = 12; // will give an error
^
1 error

Advertisements