What is meant by immutable?

后端 未结 17 1559
天命终不由人
天命终不由人 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 02:57

    1. In large applications its common for string literals to occupy large bits of memory. So to efficiently handle the memory, the JVM allocates an area called "String constant pool".(Note that in memory even an unreferenced String carries around a char[], an int for its length, and another for its hashCode. For a number, by contrast, a maximum of eight immediate bytes is required)
    2. When complier comes across a String literal it checks the pool to see if there is an identical literal already present. And if one is found, the reference to the new literal is directed to the existing String, and no new 'String literal object' is created(the existing String simply gets an additional reference).
    3. Hence : String mutability saves memory...
    4. But when any of the variables change value, Actually - it's only their reference that's changed, not the value in memory(hence it will not affect the other variables referencing it) as seen below....

    String s1 = "Old string";

    //s1 variable, refers to string in memory
            reference                 |     MEMORY       |
            variables                 |                  |
    
               [s1]   --------------->|   "Old String"   |
    

    String s2 = s1;

    //s2 refers to same string as s1
                                      |                  |
               [s1]   --------------->|   "Old String"   |
               [s2]   ------------------------^
    

    s1 = "New String";

    //s1 deletes reference to old string and points to the newly created one
               [s1]   -----|--------->|   "New String"   |
                           |          |                  |
                           |~~~~~~~~~X|   "Old String"   |
               [s2]   ------------------------^
    

    The original string 'in memory' didn't change, but the reference variable was changed so that it refers to the new string. And if we didn't have s2, "Old String" would still be in the memory but we'll not be able to access it...

提交回复
热议问题