Thursday, August 22, 2019

Final Vs Immutability in Java

Final: final is a modifier in Java, this is used for class, method and variable also. When we declared a variable with final keyword, it’s value can’t be modified, essentially, a constant.
  • final modifier is applicable for variable but not for objects,
  • final ensures that the address of the object remains the same.
  • final means that you can’t change the object’s reference to point to another reference or another object, but you can still change its state (using setter methods e.g). 
  • By declaring a reference variable as final, we can't get any immutability nature, Even though reference variable is final. We can perform any type of change in the corresponding Object. But we cant perform reassignment for that variable.
Immutability: In simple terms, immutability means unchanging over time or unable to be changed. In Java, we know that String objects are immutable means we cant change anything to the existing String objects.
  • Immutability applicable for an object but not for variables.
  • Immutable means that the object’s actual value can’t be changed, but you can change its reference to another one.
  • Immutable suggests that we can’t change the state of the object once created.
Example:- final object reference test.

public class FinalObjectReferenceTest {

 public static void main(String[] args) {

  final User user = new User(10); // Line no. 6 
  user.setName("Sanjeev");
  System.out.println(user.getName());

  user.setName("Rajeev");
  System.out.println(user.getName());

  user = new User("Amit"); // Line no. 13
 }
}

class User {

 private int num;
 private String name;

 public User(int num) {
  this.num = num;
 }

 public User(String name) {
  this.name = name;
 }

 public int getNum() {
  return num;
 }

 public void setNum(int num) {
  this.num = num;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
}
Output:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 The final local variable user cannot be assigned. It must be blank and not using a compound assignment

 at FinalObjectReferenceTest.main(FinalObjectReferenceTest.java:13)

In the above example you can see. we can change the values of object but we can not change the value of reference variable "user" as once we assign it at line number 6. we can not reassign to final user variable.

No comments:

Post a Comment