What is meant by immutable?

后端 未结 17 1800
天命终不由人
天命终不由人 2020-11-22 02:27

This could be the dumbest question ever asked but I think it is quite confusing for a Java newbie.

  1. Can somebody clarify what is meant by immutable? <
17条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 03:08

    String s1="Hi";
    String s2=s1;
    s1="Bye";
    
    System.out.println(s2); //Hi  (if String was mutable output would be: Bye)
    System.out.println(s1); //Bye
    

    s1="Hi" : an object s1 was created with "Hi" value in it.

    s2=s1 : an object s2 is created with reference to s1 object.

    s1="Bye" : the previous s1 object's value doesn't change because s1 has String type and String type is an immutable type, instead compiler create a new String object with "Bye" value and s1 referenced to it. here when we print s2 value, the result will be "Hi" not "Bye" because s2 referenced to previous s1 object which had "Hi" value.

提交回复
热议问题