Comparison of Java reference types and base types

Source: Internet
Author: User

Reference types and basic types of classification, not written, online there are a lot.

We know:
When two basic types use "= =" comparisons, they compare values .
When two reference types use "= =" comparisons, they compare the addresses .
When two reference types use method Equals () comparisons, they compare values .

But when the base type and his wrapper class (reference type) Use the "= =" comparison,
And what about their results?

Here we use integers and int for instructions.
Integer is the wrapper class for Int. int basic type, Integer is reference type.
Look at an example:

int i = 1234;
Integer i1 = new Integer (1234);
Integer i2 = new Integer (1234);
System.out.print ("I1 = = i2:" + (I1 = = I2));
System.out.println ("\ti1.equals (I2):" + (I1.equals (I2)));
System.out.print ("i = = I1:" + (i = = I1));
System.out.println ("\t\ti1.equals (i):" + (I1.equals (i)));
System.out.print ("i = = I2:" + (i = = I2));
System.out.println ("\t\ti2.equals (i):" + (I2.equals (i)));

Print:
I1 = = I2:false I1.equals (i2): True
i = = I1:true I1.equals (i): true
i = = I2:true I2.equals (i): true

We can see i = = i1, i = = I2, I1!= I2,
But using equals () they are all equal.

Then let's look at the method equals () in the integer class in jdk1.8.

    public boolean equals (Object obj) {
        if (obj instanceof Integer) {return
            value = = ((Integer) obj). Intvalue ()
        ; return
        false;
    }

You can observe the use of equals (), and they compare the values .

Summary: When comparing the base type with his wrapper class (reference type) using "= =" and method equals (), they compare values .

Integer and other basic types are the same, we are interested to be able to prove that I am not in the written.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.