1.String类有一个特殊的创建方法,就是使用""双引号来创建.例如new String("i am")实际创建了2个String对象,一个是"i am"通过""双引号创建的,另一个是通过new创建的.只不过他们创建的时期不同, 一个是编译期,一个是运行期!
2.java对String类型重载了+操作符,可以直接使用+对两个字符串进行连接。
3.运行期调用String类的intern()方法可以向String Pool中动态添加对象。
4.单独使用""引号创建的字符串都是常量,编译期就已经确定存储到String Pool中。
5.使用new String("")创建的对象会存储到heap中,是运行期新创建的。
6.使用包含变量的字符串连接符如"aa" + s1创建的对象是运行期才创建的,存储在heap中。
7.面试题:
String s1 = new String("s1") ;
String s2 = new String("s1") ;
上面创建了几个String对象?
答案:3个 ,编译期Constant Pool中创建1个,运行期heap中创建2个.
那么string + 基本类型呢?
String a = "a1";
String b = "a" + 1; //1也是常量
System.out.println((a == b)); //result = true
String a = "atrue";
String b = "a" + true; //true当然也是常量
System.out.println((a == b)); //result = true
String a = "a3.4";
String b = "a" + 3.4;
System.out.println((a == b)); //result = true
String a = "ab";
final String bb = "b"; //直接赋值的终态变量
String b = "a" + bb;
System.out.println((a == b)); //result = true
String a = "ab";
final String bb = getBB(); //getBB在运行时才能确定
String b = "a" + bb;
System.out.println((a == b)); //result = false
private static String getBB() {
return "b";
}