字符串拼接理解

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。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值