srings are actually immutable, i.e. once allocated memory they cannot be change.and this feature is actually used to share string contents with other variables.so s2 can point to s1 and ultimately only one object is created.
infact if we have string s1="hello world"; and s2 as a substring of s1 then to only 1 instance is created.
i hope ur not confused now...or more confused...
Teach me the art of forgetting, for I always remember wat I have forgotten.
I'm a fan of checking out the source code to see what happens, rather than resorting to idle speculation. Here is some code from String:
Now the poster's comment "s2 as a substring of s1 then to only 1 instance is created." is confusing. I certainly don't know what he was trying to say, But if I let code do the talking:
In this code snippet, that are two distinct string objects (referred to by s1 and s2) but that share the same char. The fact that substring can result in char sharing can either be a good thing or a bad thing. It's good if sharing gains you efficiency, but what if you've got a big String and all you want to do is refer to a bit of it and throw away the rest? String sometimes maligned constructor String(String original) can help. For why it can be useful, check out its source code, too: