[Reading notes] auto-boxed traps and = = with equals

Source: Internet
Author: User

Take a look at a piece of code, from Zhou Zhiming's "in-depth understanding of Java virtual machines."

 Integer a = 1;        Integer b  = 2;        Integer c  = 3;        Integer d  = 3;        Integer e  = 321;        Integer f  = 321;        Long g  = 3l;        System.out.println (c  == D); System.out.println (e  == f);//There's a integercache-128~127 problem here System.out.println (        c  = = (a + b));        System.out.println (C.equals (a  + b));        System.out.println (g  = = (a + b));//automatic unpacking and automatic packing? System.out.println (G.equals (a  + b));//Because both A and B are integer types, the arithmetic operation is an integer type, and long is not a type, so is false, see the source code behind. equals does not deal with the problem of data transformation, the type is different and does not compare values. 

Output:

Truefalsetruetruetruefalse

Let's look at the difference between = = and equals in Java:

= = Comparison reference. If the object is not a composite data type but a base type, the comparison is also a value.

Equals is the value that is compared.

Then look at the source of equals in the integer class:

   Public Boolean equals (Object obj) {        ifinstanceof  Integer) {            return value = = ((Integer) obj). Intvalue ();        }         return false ;    }

Then look at the author's explanation in the original book:

the "= =" Operation of the wrapper class (referred to as Integer, in contrast to int) does not automatically unpack without encountering arithmetic operations, and their equals () method does not handle the relationship of data transformation.

[Reading notes] auto-boxed traps and = = with equals

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.