That's not necessary true. Example:
String s1 = "hello";
String s2 = "hello";
System.out.println(s1 == s2); // true
but:
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2); // false
Now the second form is discouraged. Some (including me) think that String
shouldn't even have a public constructor. A better version of the above would be:
String s1 = new String("hello").intern();
String s2 = new String("hello").intern();
System.out.println(s1 == s2); // true
Obviously you don't need to do this for a constant String
. It's illustrative.
The important point about this is that if you're passed a String
or get one from a function you can't rely on the String
being canonical. A canonical Object
satisfies this equality:
a.equals(b) == b.equals(a) == (a == b)
for non-null
instances a
, b,
of a given Class
.
String.substring
does not allocate a newchar[]
is now no longer true. See this answer. – Fenella