开发者

Java String object creation [duplicate]

开发者 https://www.devze.com 2023-01-01 17:03 出处:网络
This question alr开发者_如何学运维eady has answers here: Closed 12 years ago. Possible Duplicate:
This question alr开发者_如何学运维eady has answers here: Closed 12 years ago.

Possible Duplicate:

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

Hi,

1) What is difference in thers two statements:

String s1 = "abc";

and

String s1 = new String("abc")

2) as i am not using new in first statement, how string object will be created

Thanks


The first will use a fixed String that will be compiled in the code. The second variant uses the fixed String and creates a new String by copying the characters. This actually creates a new separate object in memory and is not necessary, because Strings are immutable. For more information, you can read this thread.

The main advantage of having internalized strings is that the performance is better (e.g. through caching etc.).

As a programmer there is no real upside to creating a new String, unless you come by the following example:

String sentence = "Lorem ipsum dolor sit amet";
String word = sentence.substring(5);

Now the word has a reference to the sentence (substring does not copy the characters). This is efficient while the sentence is also used, but when this one is thrown away you use a lot more memory than needed. In that case a new String can be created:

word = new String(word);


In the first case, the compiler knows the value of the String s1. Thus, all strings with the same value will use the same memory locations:

String s1 = "abc";
String s2 = "abc";

Although there are two String references (s1 and s2), there is only one "abc" sequence in memory. The new operator is not needed because the compiler does the job.

In the second case, the compiler doesn't perform the evaluation of the String value. Thus, the sentence will generate a new instance of String, at runtime:

String s1 = "abc";
String s2 = new String("abc");

The constant "abc" in line 1 references the same memory as the constant "abc" in line 2. But the net effect of line 2 is the creation of a new String instance.

0

精彩评论

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