浅谈String类的种种性质(一)

 1 package testBlog;
 2 
 3 
 4 public class Test {
 5     
 6     public static void main(String[] args) {
 7         String a = "hello";
 8         String b = new String("hello");
 9         System.out.println(a==b);//结果是false
10         System.out.println(a.equals(b));//结果是true
11     }
12 }

由此可见,在String中,"=="符号比较的实际上是内存地址.由于使用了new,故开辟了新的堆内存空间,所以两个String a和b的内存地址是不一致的.

因此,在String的比较中,使用equals最合适.

 

 

 

 

 1 package testBlog;
 2 
 3 
 4 public class Test {
 5     
 6     public static void main(String[] args) {
 7         String str = "hello";
 8         System.out.println("hello".equals(str));//结果是true
 9     }
10 }

这里出现了一个很有意思的现象,字符串"hello"直接调用了equals()方法.

由此可见:字符串常量本质上是一个String类匿名对象.而String a = "hello";这样的语句,实际上是给一个匿名对象赋了一个名字(栈内存)而已.

posted on 2017-12-27 16:59  三盛乙烯  阅读(113)  评论(0编辑  收藏  举报

导航