开发者

How many Java string objects created in the code String s="abc"+"xyz";?

开发者 https://www.devze.com 2023-03-17 02:18 出处:网络
How many Java string objects will be created in the following statement? String s = \"abc\" 开发者_运维知识库+ \"xyz\";

How many Java string objects will be created in the following statement?

String s = "abc" 开发者_运维知识库+ "xyz"; 

I guess three?


The compiler creates 1 String per JVM start, because the compiler can determine the resulting String at compile time, it is interned and statically stored in the JVM's String Table.


FYI, if the statement were concatenating variables (not determinable at runtime), 1 String would be created, but it would create a StringBuilder too. The code would compile to:

new StringBuilder().append(abcVar).append(xyzVar).toString()


The answer is one global String object per program run, and zero new String objects per statement execution. This is because the Java Language Specification says the expression "abc" + "xyz" is a compile-time constant [0], and that no new String object will be created when the statement is executed [1].

References

[0]: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#5313

Examples of constant expressions:

"The integer " + Long.MAX_VALUE + " is mighty big."

[1]: http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.18.1

If only one operand expression is of type String, then string conversion is performed on the other operand to produce a string at run time. The result is a reference to a String object (newly created, unless the expression is a compile-time constant expression (§15.28)) that is the concatenation of the


There are three ways to create strings in java

1) we can create a string just by assigning a group of characters to a string type variable

eg:

     String s;  //declare String type variable,  
     s="hello"; //assign a group of characters to it

2)we can create an object to string by allocating memory using new operator.This is just like creating an object to any class.

eg: String s =new String("Hello");

3) We can creating the strings is by converting the character arrays into string.

eg: char arr[] = {'p','r','a','s','h','a','n','t'};

0

精彩评论

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