background image

java 中 equals ==的区别 

值类型是存储在内存中的堆栈(以后简称栈),而引用类型的变量在栈中仅仅是存储引用类型变量的地址,而

其本身则存储在堆中。

==操作比较的是两个变量的值是否相等,对于引用型变量表示的是两个变量在堆中存储的地址是否相同,即栈

中的内容是否相同。

equals 操作表示的两个变量是否是对同一个对象的引用,即堆中的内容是否相同。

==比较的是 2 个对象的地址,而 equals 比较的是 2 个对象的内容。

显然,当

equals 为 true 时,==不一定为 true;

一、

String 中的 equals 和==

1、

public class TestString {

     public static void main(String[] args) {

         String s1 = "Monday";

         String s2 = "Monday";

     }

}

上面这段程序中,到底有几个对象呢?

来检测一下吧,稍微改动一下程序

public class TestString {

     public static void main(String[] args) {

         String s1 = "Monday";

         String s2 = "Monday";

         if (s1 == s2)

             System.out.println("s1 == s2");

         else

             System.out.println("s1 != s2");

     }

}

编译并运行程序,输出:

s1 == s2

说明:

s1 与 s2 引用同一个 String 对象 -- "Monday"!

2.

再稍微改动一下程序,会有更奇怪的发现:

public class TestString {

     public static void main(String[] args) {

         String s1 = "Monday";

         String s2 = new String("Monday");

         if (s1 == s2)

             System.out.println("s1 == s2");

         else

             System.out.println("s1 != s2");