This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Please take a look at the following two codes...orWhat is the difference between these? All I see is that the first one assigns s to the immutable string object abcdef.
The 2nd one creates an immutable string object abcdef and then puts in inside the new String object which is then in turn assigned to s String object.
However both is doing the same purpose. So why in the world do we have two ways of doing the same thing? Can anyone please give me ideas when to use which one?
Yeep just saw the previous post by someone else...Though I do not understand the explanation....
Anyhow thanks for your reply...I think I will just take it for granted that there are two ways of doing the same thing without any potential benefits...except in one the string is left on the heap for "potential" future use and in another it isn't.!
except in one the string is left on the heap for "potential" future use and in another it isn't.!
That is not correct. The String you write as a literal is put onto the heap at class-loading time and stays on the head until the class is unloaded. It is reused if an identical String literal is written anywhere, even in a different class. So in the first instance you have one String object and in the second two String objects, which are identical to each other.
You are correct to say there is no benefit; since String is an immutable class, there is hardly ever any use for two identical Strings.
Somebody did once say you can use several identical Strings as lock objects, which is one potential use. Remember String is a library class, and you tend to put as many methods/constructors in library classes as possible, just in case somebody wants to use them. Once you have published a String class with a copy constructor, you can never remove that copy constructor in case somebody has already used it. If you remove the copy constructor you will break all their old code.
Rahul P Kumar
Joined: Sep 26, 2009
Joined: Oct 13, 2005
[deleted]Moving the part about questions to our Ranch Office forum. All the deleted text should be available here.
Please continue discussion about copy constructors and Strings here.
Joined: Oct 13, 2005
I mistakenly deleted the first post this morning when I moved this thread. Jaikiran Pai kindly showed me where I could find the alterations, so I have been able to replace the relevant code in the first post.