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?
It’s supposed to be an efficiency measure. i.e. when you’re taking a substring you won’t create a new char array, but merely create a window onto the existing char array.
Is this worthwhile ? Maybe. The downside is that it causes some confusion (e.g. see this SO question), plus each
Stringobject needs to carry the offset info into the array, even if it’s not used.EDIT: This behaviour has now changed as of Java 7. See the linked answer for more info