= In Java.

Source: Internet
Author: User

See the following code:

public static void main(final String[] args) {     Integer a = new Integer(100);     Integer b = 100;     System.out.println(a == b);  }

What is the output of this code? I believe many people will easily guess: false, because the addresses of objects A and B are different, it is false to compare them with "=. Congratulations! You are correct.
Let's look at the following code:

public static void main(final String[] args) {     Integer a = 100;     Integer b = 100;     System.out.println(a == b);  }

You may answer, this is nothing different, so it is still false. Unfortunately, if you execute the above Code, the result is true.
 
The above code may surprise you. Well, let's look at the following code:
Is the result true? Unfortunately, if you execute the above Code, the result is false.

public static void main(final String[] args) {     Integer a = 156;     Integer b = 156;     System.out.println(a == b);  }

Are you surprised? Then let's look at the following code:

public static void main(final String[] args) {     Integer a = Integer.valueOf(100);     Integer b = 100;     System.out.println(a == b);  }

The final result, as you may have guessed, is true.

The first code: = compare the address. If the addresses of the two objects are different, it must be false!

Code 2: JDK uses the metadata mode when data is between-128-127. That is, the same address corresponding to multiple references.

In this way, the third code is easy to understand. When it is greater than this range, it is different objects. The effect of the fourth code is the same as that of the second code.

 

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.