Java creates a single immutable object per string, but will reuse literals for performance gains.
This line creates an immutable string s1
String s1 = "abc";
Will reference the same string literal as s1
since this is a literal and can be optimized by the compiler.
String s2 = "abc";
This is an identity comparison, you are asking are S1 and S2 the same object, not the same string. Since the compiler has optimized by makeing the two objects reference the same immutable string this returns true.
System.out.println(s1 == s2);
This creates 2 immutable strings, then a third string is created at runtime. Since the runtimecant guarantee that it can find an already existing string to reference efficently it just creates a new object and create a new immutable string s3
String s3 = "a";
s3 = s3 + "bc";
This is false, as they are two separate data objects.
System.out.println(s1 == s3);
Note String equality returns true, here is how we compare the contents of the string object, not the object location. That is the first comparison checks for identity, the second checks for equality.
System.out.println(s1.equals(s3));
Java knows creating an Data object for every step of the string concatenation process is very ineffiecent. To help with the java hava the StringBuilder
api which does more performent concats.
String s = "a";
s += "b";
s += "c";
s += "d";
s += "e";
results in '9' string objects being created and written to memory ...
("a", "b", "ab", "c", "abc", "d", "abcd", "e", "abcde")
The string builder helps
StringBuilder sb = new StringBuilder();
sb.append("a");
sb.append("b");
sb.append("c");
sb.append("d");
sb.append("e");
Is more effcient as it performs one single concat and results in better memory usage.
("a", "b", "c", "d", "e", "abcde")