I\'ve been studying Java String for a while. The following questions are based on the below posts
Java String is special
Immutability of String in java
Note that in your example, the reference is changed and not the object it refers to, i.e. b
as a reference may be changed and refer to a new object. But that new object is immutable, which means its contents will not be changed "after" calling the constructor.
You can change a string using b=b+"x";
or b=new String(b);
, and the content of variable a
seem to change, but don't confuse immutability of a reference (here variable b
) and the object it is referring to (think of pointers in C). The object that the reference is pointing to will remain unchanged after its creation.
If you need to change a string by changing the contents of the object (instead of changing the reference), you can use StringBuffer
, which is a mutable version of String.
From the Java Oracle documentation:
Strings are constant; their values cannot be changed after they are created.
And again:
String buffers support mutable strings. Because String objects are immutable they can be shared.
Generally speaking: "all primitive" (or related) object are immutable (please, accept my lack of formalism).
Related post on Stack Overflow:
About the object pool: object pool is a java optimization which is NOT related to immutable as well.
1) Immutability: String will be immutable if you create it using new or other way for security reasons
2) Yes there will be a empty entry in the string pool.
You can better understand the concept using the code
String s1 = new String("Test");
String s2 = new String("Test");
String s3 = "Test";
String s4 = "Test";
System.out.println(s1==s2);//false
System.out.println(s1==s3);//false
System.out.println(s2==s3);//false
System.out.println(s4==s3);//true
Hope this will help your query. You can always check the source code for String class in case of better understanding Link : http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java
String A = "Test"
String B = "Test"
Now String B called
"Test".toUpperCase()which change the same object into
"TEST", so
Awill also be
"TEST"` which is not desirable.
String is immutable because it does not provide you with a mean to modify it. It is design to avoid any tampering (it is final, the underlying array is not supposed to be touched ...).
Identically, Integer is immutable, because there is no way to modify it.
It does not matter how you create it.
String is immutable means that you cannot change the object itself no matter how you created it.And as for the second question: yes it will create an entry.