1

This is a bit of Java String 101. I came across this recently in some existing code. My initial reaction is that this is redundant

car.setDetails(new String(someStringBufferObj.toString));

In my opinion even this would be redundant...

car.setDetails(new String(someOtherStringObj));

because String is immutable so there is never a risk that the car details would be changed accidentally (by changing someOtherStringObj) in a later line of code

Are am I wrong?

2
  • 2
    Yeah you are right. Both of those snippet is simply creating unnecesary strings, provided your someOtherString is a String only. Commented Feb 13, 2013 at 14:37
  • Not necessarily. I agree re. example 1 but not re. example 2. See my answer below Commented Feb 13, 2013 at 14:45

2 Answers 2

2

The first snippet above looks unnecessary. However the second may be necessary. Consider the following.

The constructor String(String) is useful since it'll take a copy of the underlying character array of the original string.

Why is this useful ? You have to understand that a string object has a character array underlying it, and getting a substring() of an existing string actually uses that original character array. This is a flyweight pattern. Consider the following

String s = longstring.substring(2,4);

The string s points to the character array underlying longstring (somewhat unintuitively). If you want to bin longstring (using garbage collection) the underlying character array won't be binned since s still references it, and you end up consuming a potentially huge amount of memory for a 2 character string.

The String(String) constructor resolves this by creating a new character array from that referenced by the string being used to construct from. When the original string is removed via garbage collection its character array won't be referenced by the substring() result and hence that will be removed too.

Note that this behaviour has changed very recently in Java (release 7u4, I think) and strings don't support the above mode of operation anymore.

Sign up to request clarification or add additional context in comments.

1 Comment

And whenever or not it's usefull, I don't think it's redundant. Doesn't that word cover an entirely other thing?
0

You're absolutely right Rob, there's no need to new up a String in this instance. Just providing a call to someStringBufferObj.toString() should be sufficient!

2 Comments

someStringBufferObj != someOtherStringObj
@PremGenError. He is probably referring to the first snippet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.