Java – operator = = wrap differential behavior on class objects

Any body can explain what happened in my output

static void main(String args[])
{
    Integer aa = Integer.valueOf("12");
    Integer bb = Integer.valueOf("12");
    if(aa==bb)System.out.println("aa==bb");
    if(aa!=bb)System.out.println("aa!=bb");
    Integer ee = new Integer("12");
    Integer ff = new Integer("12");


    if(ee==ff)System.out.println("ee==ff");
    if(ee!=ff)System.out.println("ee!=ff");
}

Output:

AA BB ==

EE value= FF

Solution

==The comparator checks the equality of objects!

String a = "a"; 
String b = "a";

// a==a is true
// a==b is false but
// a.equals(b) is true

Because integer Valueof maintains a cache of integer objects with values from - 128 to 127. Valueof (string) returns the cache object, so = = the comparison result is true

For comparison of object values, always use Equals method. For primitives such as int and long, you can use = = comparator

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>