How to create a variable that can be set only once but isn't final in Java?


Once you initialize a final variable you cannot modify its value further. i.e. You can assign value to a final variable only once. If you try to assign value to a final variable a compile time error will be generated.

Example

 Live Demo

public class FinalExample {
   final int j = 100;
   public static void main(String args[]){
      FinalExample obj = new FinalExample();
      obj.j = 500;
      System.out.println(obj.j);
   }
}

Compile time error

FinalExample.java:6: error: cannot assign a value to final variable j
   obj.j = 500;
      ^
1 error

Achieving the “final” functionality

To achieve the final functionality without actually using the final keyword −

Make the variable private and set value to it using the setter method such that if you try to invoke it for the second time it should set the previous value or throw an exception.

Example

 Live Demo

public class FinalExample {
   private Integer num;
   public void setNum(int num){
      this.num = this.num == null ? num : this.num;
   }
   private String data;
   public void setData(String data) {
      this.data = this.data == null ? data : demo();
   }
   public String demo() {
      String msg = "You cannot set value to the variable data for the second time";
      throw new RuntimeException(msg);
   }
   public static void main(String args[]){
      FinalExample obj = new FinalExample();
      obj.setNum(200);
      System.out.println(obj.num);
      obj.setNum(500);
      System.out.println(obj.num);
      obj.setData("hello");
      obj.setData("sample data");
   }
}

Output

200
200
Exception in thread "main" java.lang.RuntimeException: You cannot set value to the variable data for the second time
at SEPTEMBER.remaining.FinalExample.demo(FinalExample.java:15)
at SEPTEMBER.remaining.FinalExample.setData(FinalExample.java:12)
at SEPTEMBER.remaining.FinalExample.main(FinalExample.java:26)

Updated on: 11-Oct-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements