Immutability of Strings in Java

why string is immutable in java - geeksforgeeks
why string is immutable in java? - quora
why string is immutable in python
why string is immutable in java? - stack overflow
mutable and immutable string in java with example
how to make string mutable in java
why string is immutable in c#
why string is immutable and stringbuffer is mutable in java

Consider the following example.

String str = new String();

str  = "Hello";
System.out.println(str);  //Prints Hello

str = "Help!";
System.out.println(str);  //Prints Help!

Now, in Java, String objects are immutable. Then how come the object str can be assigned value "Help!". Isn't this contradicting the immutability of strings in Java? Can anybody please explain me the exact concept of immutability?

Edit:

Ok. I am now getting it, but just one follow-up question. What about the following code:

String str = "Mississippi"; 
System.out.println(str); // prints Mississippi 

str = str.replace("i", "!"); 
System.out.println(str); // prints M!ss!ss!pp! 

Does this mean that two objects are created again ("Mississippi" and "M!ss!ss!pp!") and the reference str points to a different object after replace() method?

Immutability of Strings in Java, Java String Pool is the special memory region where Strings are stored by the JVM. Since Strings are immutable in Java, the JVM optimizes the  The immutability of String objects does not mean that the references pointing to the object cannot change. One way that one can prevent the str reference from changing is to declare it as final : final String STR = "Hello"; Now, trying to assign another String to STR will cause a compile error.

The object that str references can change, but the actual String objects themselves cannot.

The String objects containing the string "Hello" and "Help!" cannot change their values, hence they are immutable.

The immutability of String objects does not mean that the references pointing to the object cannot change.

One way that one can prevent the str reference from changing is to declare it as final:

final String STR = "Hello";

Now, trying to assign another String to STR will cause a compile error.

Why String is Immutable in Java?, Now, since String s are immutable, the VM can't assign this value to str , so it creates a new String object, gives it a value "knowledge base" , and gives it a  Why Is String Immutable in Java? 3.1. Introduce to String Pool. The String is the most widely used data structure. Caching the String literals and 3.2. Security. The String is widely used in Java applications to store sensitive pieces of information like usernames, 3.3. Synchronization. Being

Light_handle I recommend you take a read of Cup Size -- a story about variables and Pass-by-Value Please (Cup Size continued). This will help a lot when reading the posts above.

Have you read them? Yes. Good.

String str = new String();

This creates a new "remote control" called "str" and sets that to the value new String() (or "").

e.g. in memory this creates:

str --- > ""

str  = "Hello";

This then changes the remote control "str" but does not modify the original string "".

e.g. in memory this creates:

str -+   ""
     +-> "Hello"

str = "Help!";

This then changes the remote control "str" but does not modify the original string "" or the object that the remote control currently points to.

e.g. in memory this creates:

str -+   ""
     |   "Hello"
     +-> "Help!"

Java: String is Immutable. What exactly is the meaning , String is immutable in Java. An immutable class is simply a class whose instances cannot be modified. All information in an instance is initialized when the. What is String immutablity in Java ? An object is considered immutable if its state cannot change after it is constructed. That means, once the constructor of an Immutable class has completed execution, the created instance cannot be altered. String class is immutable.

Lets break it into some parts

String s1 = "hello";

This Statement creates string containing hello and occupy space in memory i.e. in Constant String Pool and and assigned it to reference object s1

String s2 = s1;

This statement assigns the same string hello to new reference s2

         __________
        |          |
s1 ---->|  hello   |<----- s2
        |__________| 

Both references are pointing to the same string so output the same value as follows.

out.println(s1);    // o/p: hello
out.println(s2);    // o/p: hello

Though String is immutable, assignment can be possible so the s1 will now refer to new value stack.

s1 = "stack";    
         __________
        |          |
s1 ---->|  stack   |
        |__________|

But what about s2 object which is pointing to hello it will be as it is.

         __________
        |          |
s2 ---->|  hello   |
        |__________|

out.println(s1);    // o/p: stack
out.println(s2);    // o/p: hello

Since String is immutable Java Virtual Machine won't allow us to modify string s1 by its method. It will create all new String object in pool as follows.

s1.concat(" overflow");

                 ___________________
                |                   |
s1.concat ----> |  stack overflow   |
                |___________________|

out.println(s1);    // o/p: stack
out.println(s2);    // o/p: hello
out.println(s1.concat); // o/p: stack overflow

Note if String would be mutable then the output would have been

out.println(s1);    // o/p: stack overflow

Now you might be surprised why String has such methods like concat() to modify. Following snippet will clear your confusion.

s1 = s1.concat(" overflow");

Here we are assigning modified value of string back to s1 reference.

         ___________________
        |                   |
s1 ---->|  stack overflow   |
        |___________________|


out.println(s1);    // o/p: stack overflow
out.println(s2);    // o/p: hello

That's why Java decided String to be a final class Otherwise anyone can modify and change the value of string. Hope this will help little bit.

Why String is immutable in Java?, The string is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always  In short, when you are performing some operations on string objects, then new string objects are created and the original strings remain unaffected. i.e. original string objects cannot be changed. This phenomenon is called as immutability of strings.

The string object that was first referenced by str was not altered, all that you did was make str refer to a new string object.

Why String is Immutable or Final in Java, Conclusively, immutable objects are used to reduce memory usage and object creation. It increases the performance by saving the time needed to create a new​  Here are a set of diagrams to illustrate Java String's immutability. 1. Declare a string The following code initializes a string s. String s =

Immutability Of String, Since a string object is immutable, its hashcode is cached at the time of creation so that it can be used multiple times without calculation. This immutability feature​  Immutability: In simple terms, immutability means unchanging over time or unable to be changed. In Java, we know that String objects are immutable means we cant change anything to the existing String objects.

Why are strings immutable in Java?, Why String is immutable in Java? why string is immutable in Java, why string is immutable and final in java. Let's look at some of the benefits of String immutability,  String is Immutable in Java because String objects are cached in String pool. Since cached String literals are shared between multiple clients there is always a risk, where one client's action would affect all another client.

Why String is Immutable in Java?, The hashcode of string is frequently used in Java. For example, in a HashMap. Being immutable guarantees that hashcode will always the same,  Here comes the point of making String objects immutable: In the String constant pool, a String object is likely to have one or many references. If several references point to same String without even knowing it, it would be bad if one of the references modified that String value. That’s why String objects are immutable.

Comments
  • str is ONLY a reference not object itself
  • I hope this helps pushkarrajpujari.com/article/strings-in-java
  • +1 for the fictional method, it demonstrates the differnce between immutable object and others.
  • Thanks gustafc for the correct examples and clear explanation....But can you just answer the edited part in the question please? That will make my understanding clear.
  • I've never seen an answer like this before. Discussed every single detail.
  • +1 Here's an idea, immutable objects in java are like copy-by-value, you can have 2 references to a String, but you should consider them 2 separate Strings since it's immutable, and working with one of them won't affect the other
  • Java-the more you think you know, the less you actually know.
  • But in this case, the String object is 'str' which first contains the value 'Hello' and then gets assigned new value 'Help!'. What exactlyt do you mean by "The String objects containing the string "Hello" and "Help!" cannot change their values, hence they are immutable."??? Pardon me if this is a silly question. But iv got to clear it...
  • have you perchance every tried to program in C? Just read the primer on pointers and you'll understand coobird's answer perfectly.
  • See...This is what I want to avoid...I know you are a great programmer...and I am just trying to learn java here...So if you can answer my question correctly then please answer it...
  • You're confusing references and objects - str isn't the "object" it's a reference to the object. If you have String str = "Hello"; followed by String anotherReference = str; you don't have 2 String objects, you have one object (the literal "Hello") and 2 references to it (str and anotherReference).
  • I do not have the rights to edit, but if I did, I would edit coobirds 1st sentence to: "The str references can change, but the actual String objects themselves cannot."
  • Do "" and "Hello" get garbage collected?
  • @PrabinTimsina This should really be a new question. It is answered: stackoverflow.com/questions/15324143/…