开发者

Java String usage [duplicate]

This question a开发者_运维知识库lready has answers here: Closed 11 years ago.

Possible Duplicate:

What is the purpose of the expression “new String(…)” in Java?

When should I use new String() and when should I use ""


The only time you should use a String constructor that takes a String argument is when the argument is a substring of a very large string, and you expect the substring to live much longer than the large string. such as

public String getDetails() {
   String largeString = getMassivelyLargeStringFromSomewhere();
   return new String(largeString.substring(2, 5));
}

the reason for this, is that when you do substring, you don't actually create a new char array, you merely reference the character array (with an offset and length) from the original String.

Therefore, the original char array from the original string cannot be garbage collected because the smaller string maintains a reference to it. By doing new String(x) you copy the data and remove the reference, so that when the larger string can otherwise be gc'ed it will.


If you are just trying to initialize a string variable whose value you don't know yet "" should be fine. Difference is "" uses same empty string every time, while new String() will create new object on java heap every time.


When you think of using new String() you probably need a StringBuffer.


If it's just for creating an empty string, then use "".


Just use "". It was created for this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜