Java automatic unpacking traps and java traps

Source: Internet
Author: User

Java automatic unpacking traps and java traps

Java automatic unpacking is widely used. But there are some "traps ". Let's look at a piece of code:

 

public static void main(String[] args) {Integer a=1;Integer b=2;Integer c=3;Integer d=3;System.out.println(c==(a+b));System.out.println(c==d);System.out.println(c.equals(d));Integer f=200;Integer e=200;System.out.println(e==f);System.out.println(e.equals(f));}

Print result:

True

True

True

False

True

If all the preceding operations are automatically split, the printed result should be true. The = symbol does not automatically split the box, so the above problem occurs. But after a closer look, someone will say, isn't it clearly c = d? To solve the mystery, we must understand the packing process. Let's take a look at the disassembly result of the above Code:



From the code snippet above, we can see that the class method Integer. valueOf was called. Let's take a look at this class method:

  /**     * Returns a {@code Integer} instance for the specified integer value.     * <p>     * If it is not necessary to get a new {@code Integer} instance, it is     * recommended to use this method instead of the constructor, since it     * maintains a cache of instances which may result in better performance.     *     * @param i     *            the integer value to store in the instance.     * @return a {@code Integer} instance containing {@code i}.     * @since 1.5     */    public static Integer valueOf(int i) {        return  i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];    }

    /**     * A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing     */    private static final Integer[] SMALL_VALUES = new Integer[256];

Seeing the above code, I believe it is clear why the above results have occurred. Because [-128,127] is cached.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.