Java:integer equals vs. = =

Source: Internet
Author: User

As of Java 1.5, you can pretty much interchange with in Integer int many situations.

However, I found a potential defect in my code that surprised me a bit.

The following code:

Integer cdict = ...; integer CDSCT = ...; ... if (cdict! = NULL && CDSCT! = NULL && cdict! = CDSCT) mismatch = true;

Appeared to is incorrectly setting mismatch when the values were equal, although I can ' t determine under what circumstance S. I set a breakpoint in Eclipse and saw that the Integer values were both 137, and I inspected the Boolean expression and I T said it is false, but when I stepped over it, it is setting mismatch to true.

Changing the conditional to:

if (cdict! = NULL && CDSCT! = null &&!cdict.equals (CDSCT))

Fixed the problem.

can anyone shed some light on what this happened? So far, I had only seen the behavior in my localhost on my own PC. In this particular case, the code successfully made it past about comparisons, but failed on 2. The problem was consistently reproducible.

If It is a prevalent problem, it should being causing errors on our other environments (Dev and test) Reported the problem after hundreds of tests executing this code snippet.

Is it still not legitimate to use to == compare the Integer values?

In addition to all the fine answers below, the following-StackOverflow link has quite a bit of additional information. It actually would has answered my original question, but because I didn ' t mention autoboxing in my question, it didn ' t sh ow up in the selected suggestions:

Why can ' t the COMPILER/JVM just do autoboxing "just work"?

The JVM is caching Integer values. = = only works for numbers between-128 and 127Http://www.owasp.org/index.php/J Ava_gotchas#immutable_objects_.2f_wrapper_class_caching

Java:integer equals vs. = =

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.