I always thought if I do String s = "Hello World".substring(0, 5)
, then I just get a new string s = "Hello"
. This is also documented in the Java API doc: "Returns a new string that is a substring of this string".
But when I saw the following two links, I began to doubt.
What is the purpose of the expression "new String(...)" in Java?
String constructor considered useless turns out to be useful after all
Basically, they say if I use String s = "Hello World".subString(0, 5)
, I still get a String which holds "Hello World"'s char array.
Why? Does Java really implement substring in this way? Why in this way? Why not just return a brand new shorter substring?