java的==和equal的区别(一)

java的==和equal的区别

“==”是用来比较两个String对象在内存中的存放地址是否相同的。例如,

1
2
3
4
5
6
7
8
9
String test1 = "test";
String test2 = "test";
 
String test3 = new String(test2);
String test4  =new String(test2);
 
 
blooean result1 = (test1==test2);
blooean result2 = (test3==test4);

其中:result1为true,result2为false。

原因:程序在运行时有一个字符串缓存机制,当String test1 = "test"的时候,程序先从缓存池中查找是否有相同的String 对象,如果有的话就不会重新生成而是用缓存池中的字符串对象;如果在字符串缓存池中没找到相同的字符串对象时才会在内存中开辟一块内存区新建字符串对象。对于test1,当test1建立以后会将“test”字符串放入缓存池中,所以运行 String test2 = "test"的时候就会直接从缓存池中取出相同的对象,也就说,test1和test2的内存地址是相同的,所以,result1是true。对于new来说,每new一次就会在内存中开辟一片内存区域,test3和test4的内存地址是不同的,所以result2是false。

再说“equal方法”:

在String中的equal方法是比较两个String对象的内容是否相同。(字符串内容相同返回true,不同返回false

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");

    if (s1.equals(s2)) System.out.println("s1 equals s2");

    else

    System.out.println("s1 not equals s2");

    }

    }

我们将s2用new操作符创建

    程序输出:

    s1 != s2

    s1 equals s2

    说明:s1 s2分别引用了两个"Monday"String对象,但是对象内容是相同的都是Monday

如果不明白为什么 s1 equals s2  是true 的话,可以查看我的博客 “java 的==和equals的区别(二)

原文地址:https://www.cnblogs.com/111testing/p/6714433.html