String Pool/String Interning
When you create a new string:
String s = "text";
//What is really happening is that it kind of creating a new instance like String s = new ("text")
//But it is not creating a new instance, it is using the string pool
Never use the new operator for creating a new string as it is not using the string pool
String s = "text"; //Good practice - Using string pool
String s = new String("text"); //Bad practice - Not using string pool
http://www.journaldev.com/797/what-is-java-string-pool
https://stackoverflow.com/questions/3052442/what-is-the-difference-between-text-and-new-stringtext
String interning:
In addition to what was already said, String literals [ie, Strings like"abcd"
but not likenew String("abcd")
] in Java are interned - this means that every time you refer to "abcd", you get a reference to a singleString
instance, rather than a new one each time.
So you will have:
String a = "abcd";
String b = "abcd";
a == b; //True
But if you had:
String a = new String("abcd");
String b = new String("abcd");
//then it's possible to have
a == b; // False
String Immutability
- Once you create a string you can't modify it, unless you re assign it
String s1 = "Hello";
String s2 = s1;
// s1 and s2 now point at the same string - "Hello"
s1 = "Help!"; //Setting s1 to "Help!" only changes the reference, while the String object it originally referred to remains unchanged.
System.out.println(s2); // still prints "Hello"
https://stackoverflow.com/questions/1552301/immutability-of-strings-in-java