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 String object 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
Answer from Brian Agnew on Stack OverflowVideos
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 String object 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
Turning it around, why allocate a new char[] when it is not necessary? This is a valid implementation since String is immutable. It saves allocations and memory in the aggregate.
Hey guys, I've been working on this Java homework for my class and this whole section about string manipulation is confusing me.
The homework asks to add statements that use the substring method to get the first half and second half of phrase.
I'm assuming that means using the substring method, but I always get errors trying to compile what I put in. So here's the code. I'm not exactly sure how to use the substring method in the way they ask, and my book doesn't really go over it well. Should I be creating another variable or just use what I have?