Java String相关

  例1
  String s1 = "sss111";
  //此语句同上
  String s2 = "sss111";
  System.out.println(s1 == s2); //结果为true
  例2
  String s1 = new String("sss111");
  String s2 = "sss111";
  System.out.println(s1 == s2); //结果为false
  例3
  String s1 = new String("sss111");
  s1 = s1.intern();
  String s2 = "sss111";
  System.out.println(s1 == s2);//结果为true
  例4
  String s1 = new String("111");
  String s2 = "sss111";
  String s3 = "sss" + "111";
  String s4 = "sss" + s1;
  System.out.println(s2 == s3); //true
  System.out.println(s2 == s4); //false
  System.out.println(s2 == s4.intern()); //true

       例5

  private static String a = new String("ab");
     public static void main(String[] args){
  String s1 = "a";
  String s2 = "b";
  String s = s1 + s2;
  System.out.println(s == a); //false
  System.out.println(s.intern() == a); //false
  System.out.println(s.intern() == a.intern());//true
  }

       例6

       String s1 = "ab";

       final String s2 = "a";
  final String s3 = "b";
  String s = s4 + s2;     

       System.out.println(s1 == s2); //true

       因为final变量在编译后会直接替换成对应的值,所以实际上等于s4=”a”+”bc”,而这种情况下,编译器会直接合并为s4=”       

       abc”,所以最终s1==s4。 
  

String.intern()是一个Native方法,它的作用是:如果字符常量池中已经包含一个等于此String对象的字符串,则返回常量池中字符串的引用,否则,将新的字符串放入常量池,并返回新字符串的引用’ 


   1.单独使用""引号创建的字符串都是常量,编译期就已经确定存储到String Pool中;

  2,使用new String("")创建的对象会存储到heap中,是运行期新创建的;

  3,使用只包含常量的字符串连接符如"aa" + "aa"创建的也是常量,编译期就能确定,已经确定存储到String Pool中;

  4,使用包含变量的字符串连接符如"aa" + s1创建的对象是运行期才创建的,存储在heap(堆)中;

 

    好文推荐:作者 汪神

     https://www.cnblogs.com/wangshen31/p/10404353.html#4434506

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值