String str3="hello"+" word!";
String str4="hello word!";
System.out.println(str3==str4);
//运行结果:true
原因:JVM编译器对字符串做了优化,在编译时str3就已经被优化成“hello Word!”,str3和str4指向字符串常量池同一个字符串常量,所以==比较为true。
double x = 9.987;
double y = 1;
double t = x+y;
String str3="hello"+" word!";
String str4="hello word!";
System.out.println(str3==str4);
String s = "Price is:"+x;
String st = "Total Price is:"+t;
System.out.println(s);
System.out.println(st);
System.out.println(""+x+y);
System.out.println(x+y+"");
//容易产生空指针异常
//Student s=new Student();
//s=null;
//if((s!=null)&(s.getName().equals("zs")))
//{
//}
//永远为false
//if((s!=null)&&("zs"==(s.getName()))
//正确写法
//if((s!=null)&&("zs".equals(s.getName()))
//}
“Price is”+ x,会创建两个string类型的对象,一开始先在方法区的常量池里创建“Prince is”,然后由于有一个“+”号,会马上把x这个9.987转换成string,又在方法区的常量池,string对象的属性是final。接着又在常量池创建一个string对象:Price is9.987。
string对象的创建对象的方式:一、new一个;二、string a = “123456”;三、用+号
结果:
可以看出,String类型的对象后面跟着“+”,不管后面为什么变量,都会转化成String类型的字符串,然后把他们做链接,所以会有结果9.9871.0。