What is meant by immutable?

后端 未结 17 1606
天命终不由人
天命终不由人 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...

    0 讨论(0)
  • 2020-11-22 03:01

    Immutable means that once the object is created, non of its members will change. String is immutable since you can not change its content. For example:

    String s1 = "  abc  ";
    String s2 = s1.trim();
    

    In the code above, the string s1 did not change, another object (s2) was created using s1.

    0 讨论(0)
  • 2020-11-22 03:02

    Immutable simply mean unchangeable or unmodifiable. Once string object is created its data or state can't be changed

    Consider bellow example,

    class Testimmutablestring{  
      public static void main(String args[]){  
        String s="Future";  
        s.concat(" World");//concat() method appends the string at the end  
        System.out.println(s);//will print Future because strings are immutable objects  
      }  
     }  
    

    Let's get idea considering bellow diagram,

    In this diagram, you can see new object created as "Future World". But not change "Future".Because String is immutable. s, still refer to "Future". If you need to call "Future World",

    String s="Future";  
    s=s.concat(" World");  
    System.out.println(s);//print Future World
    

    Why are string objects immutable in java?

    Because Java uses the concept of string literal. Suppose there are 5 reference variables, all refers to one object "Future".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

    0 讨论(0)
  • 2020-11-22 03:03

    One meaning has to do with how the value is stored in the computer, For a .Net string for example, it means that the string in memory cannot be changed, When you think you're changing it, you are in fact creating a new string in memory and pointing the existing variable (which is just a pointer to the actual collection of characters somewhere else) to the new string.

    0 讨论(0)
  • 2020-11-22 03:03

    As the accepted answer doesn't answer all the questions. I'm forced to give an answer after 11 years and 6 months.

    Can somebody clarify what is meant by immutable?

    Hope you meant immutable object (because we could think about immutable reference).

    An object is immutable: iff once created, they always represent the same value (doesn't have any method that change the value).

    Why is a String immutable?

    Respect the above definition which could be checked by looking into the Sting.java source code.

    What are the advantages/disadvantages of the immutable objects? immutable types are :

    • safer from bugs.

    • easier to understand.

    • and more ready for change.

    Why should a mutable object such as StringBuilder be preferred over String and vice-verse?

    Narrowing the question Why do we need the mutable StringBuilder in programming? A common use for it is to concatenate a large number of strings together, like this:

    String s = "";
    for (int i = 0; i < n; ++i) {
        s = s + n;
    }
    

    Using immutable strings, this makes a lot of temporary copies — the first number of the string ("0") is actually copied n times in the course of building up the final string, the second number is copied n-1 times, and so on. It actually costs O(n2) time just to do all that copying, even though we only concatenated n elements.

    StringBuilder is designed to minimize this copying. It uses a simple but clever internal data structure to avoid doing any copying at all until the very end, when you ask for the final String with a toString() call:

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < n; ++i) {
      sb.append(String.valueOf(n));
    }
    String s = sb.toString();
    

    Getting good performance is one reason why we use mutable objects. Another is convenient sharing: two parts of your program can communicate more conveniently by sharing a common mutable data structure.

    More could be found here : https://web.mit.edu/6.005/www/fa15/classes/09-immutability/#useful_immutable_types

    0 讨论(0)
  • 2020-11-22 03:04

    Immutable Objects

    An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code.

    Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.

    Programmers are often reluctant to employ immutable objects, because they worry about the cost of creating a new object as opposed to updating an object in place. The impact of object creation is often overestimated, and can be offset by some of the efficiencies associated with immutable objects. These include decreased overhead due to garbage collection, and the elimination of code needed to protect mutable objects from corruption.

    The following subsections take a class whose instances are mutable and derives a class with immutable instances from it. In so doing, they give general rules for this kind of conversion and demonstrate some of the advantages of immutable objects.

    Source

    0 讨论(0)
提交回复
热议问题