Final variable manipulation in Java

前端 未结 11 784
无人及你
无人及你 2020-11-28 23:28

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 immut

11条回答
  •  不知归路
    2020-11-28 23:45

    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).

提交回复
热议问题