Search code examples
javavariablesfinal

Final variable manipulation in Java


Could anyone please tell me what is the meaning of the following line in context of Java:

final variable can still be manipulated unless it's immutable

As far as I know, by declaring any variable as final, you can't change it again, then what they mean with the word immutable in above line?


Solution

  • It means that if your final variable is a reference type (i.e. not a primitive like int), then it's only the reference that cannot be changed. It cannot be made to refer to a different object, but the fields of the object it refers to can still be changed, if the class allows it. For example:

    final StringBuffer s = new StringBuffer();
    

    The content of the StringBuffer can still be changed arbitrarily:

    s.append("something");
    

    But you cannot say:

    s = null;
    

    or

    s = anotherBuffer;
    

    On the other hand:

    final String s = "";
    

    Strings are immutable - there simply isn't any method that would enable you to change a String (unless you use Reflection - and go to hell).