首页 > 其他 > 详细

==和equals的比较

时间:2017-12-12 12:06:17      阅读:198      评论:0      收藏:0      [点我收藏+]
 字符串只要new,就会产生一个新的地址
 == :比较的是地址 str1,str2存储在常量池中,内存优化,是同一个字符串
equals :比较的是内容,只要内容一样结果就为true
 1 package myeclipseFiles2;
 2 
 3 public class String1 {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7         String str1="hello";
 8         String str2="hello";
 9         String str3="Hello";
10         
11         String str4=new String("hello");
12         String str5=new String("hello");
13         //字符串只要new,就会产生一个新的地址
14         //==比较的是地址 str1,str2存储在常量池中,内存优化,是同一个字符串
15         System.out.println(str1==str3);//false
16         System.out.println(str1==str2);//true
17         System.out.println(str1==str4);//false
18         System.out.println(str4==str5);//false
19         System.out.println(str1==str3);//false
20         //equals比较的是内容,只要内容一样结果就为true
21         System.out.println(str1.equals(str4));//true
22         System.out.println(str1.equals(str3));//false
23         
24         
25     }
26 
27 }

 

 1 package myeclipseFiles2;
 2 
 3 public class String1 {
 4 
 5     public static void main(String[] args) {
 6         // TODO Auto-generated method stub
 7         String str1="Hello";
 8         String str4=new String("hello");
 9         str4="Hello";//重新赋值后,原来的str4 new出来的新地址被垃圾回收站回收成为空指针
10         System.out.println(str1==str4);//true
11     }
12 
13 }

 

==和equals的比较

原文:http://www.cnblogs.com/ztt0918/p/8026857.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!