创建字符串的几种方法之间的差异

时间:2014-05-08 14:29:26

标签: java string string-pool

创建字符串的几种方法如下所示。在评论方式的表达式之后添加问题。

String str = "test";
String str1 = new String(str);  //Will it invoke the Constructor of String(String)?
String str2 = new String("test");//Will it invoke the Constructor of String(String)?
String str3 = str; //Which Constructor will it invoke? Or str3 only reference to str and "test" without being constructed?
String str4 = "test";//Which Constructor will it invoke? Or str4 only reference to str and "test" without being constructed?
String strnew = new String("testnew");//Will this expression create "testnew" in String Constant Pool before it creates strnew?

另外一个问题:创建str3和str4的方式之间有什么区别吗?

1 个答案:

答案 0 :(得分:5)

  

每当你在JAVA中调用new时,它会在堆中创建一个对象,显然它也会调用构造函数。

     

字符串文字将转到String Constant Pool

它可能会帮助您直观地理解它。

enter image description here