AddThis Social Bookmark Button

In this article we will explore some misconception of Java

  1. You can't change value of a final variable.
    It is true ?that you can't change a value in the final variable. Well it is partially correct.
    Lets have a look at the following code
    public static final int PI=3.141;
    
    This is how we create a constant in Java, It is pretty much true that you can't modify the value PI no matter how.
    But saying "You can't change the vlaue of a final variable" is wrong, so very wrong when the variable type is not a primitive type . Have a look at the following code. 
    public class Test {
            public class Test {
            public static final State STATE=new State();
            public static void main(String args[]){
                System.out.println("Status: "+STATE.getStatus());
                STATE.setStatus("But,See I got changed");
                System.out.println("Status after reassignment:"+STATE.getStatus());
                }
            }
    class State {
            private String status="My Object is assigned to a final variable,And I think I can't change";
            public String getStatus() {
                return status;
            }
            public void setStatus(String status) {
                this.status = status;
            }
    }
    

    In the above class Test, we have a final variable STATE, which is assigned an object reference of State class. And then in main method we are trying to modify the status field of State object which is assigned to a STATE constant(technically).The State class is nothing special , we have a instance field status as type String with some value assigned.And a getter/setter to access the private field state.
    Now execute this program and you will see the result yourself.
    Bottom line: If a final variable is a reference type then the object it is referring to is still mutable,meaning that we can modify the states(with a condition that the class/object is mutable) A final variable can't be reassigned once assigned no matter if the variable is primitive type of reference type. But if a final variable of reference type doesn't restrict you to modify the state of the reference type ( applicable only if the reference type i.e the class allows modification).