Java Automatic Disassembly box introduction, Java disassembly box Introduction

Source: Internet
Author: User

Java Automatic Disassembly box introduction, Java disassembly box Introduction

During the interview, the interviewer often asks the Java disassembly box when asking basic questions. This is not a very difficult question, but if you do not pay attention to it during self-study, it is possible to face it, so I will summarize this issue and promote it together!

I. disassembly Box Concept

The so-called disassembly box is the conversion between the basic types and reference types of java since JDK1.5.

1.1 binning

The unboxing action is to convert Long, Integer, Double, Float and so on to the corresponding reference type of the first letter of the basic data type into the basic data type.

1.2 packing

Packing means that the basic data types of byte, int, short, long, double, float, boolean, and char are not declared as the corresponding reference type when defining the data type, the action that automatically converts to the reference type under the processing of the compiler is called packing.

II. Application of disassembly box

After JDK1.5, it is convenient to convert the basic and reference types:

Package com. hzp. CZX;/*** test the disassembly box * @ author night lone cold * @ version 1.1.1 */public class TestDemo {/*** after the disassembly box JDK1.5 */public static void first () {Integer I = 7; // basic type --> reference type int j = I; // reference type --> basic type System. out. println (j);}/*** disassembling box JDK1.4 */public static void second () {Integer I = new Integer (78); int j = I. intValue (); System. out. println (j);}/*** Test Method * @ param args */public static void main (String [] args) {first (); second ();}}

The above describes some basic points and usage methods of the disassembly box, but there are some points to note when using the disassembly box. The following will summarize these points of attention.

Iii. Notes

First, paste the following code:

Package com. ygh. CZX; /*** analysis on the range of java disassembly boxes * @ author night lone cold * @ version 1.1.1 */public class Test {/*** take Integer type as an example */public static void first () {Integer I = new Integer (124); Integer j = new Integer (124); System. out. println (I = j); // false Integer a1 =-128; Integer a2 =-128; System. out. println (a1 = a2); // true Integer b1 =-129; Integer b2 =-129; System. out. println (b1 = b2); // false Integer c1 = 127; Integer c2 = 127; System. out. println (c1 = c2); // true Integer d1 = 128; Integer d2 = 128; System. out. println (d1 = d2); // false} public static void main (String [] args) {first ();}}

A brief explanation:

The first result is false because different objects are created, so the two are different;

But why is the second and third results different?

The following is the source code of the Integer class, which is analyzed from the source code perspective:

    /**     * Returns an {@code Integer} instance representing the specified     * {@code int} value.  If a new {@code Integer} instance is not     * required, this method should generally be used in preference to     * the constructor {@link #Integer(int)}, as this method is likely     * to yield significantly better space and time performance by     * caching frequently requested values.     *     * This method will always cache values in the range -128 to 127,     * inclusive, and may cache other values outside of this range.     *     * @param  i an {@code int} value.     * @return an {@code Integer} instance representing {@code i}.     * @since  1.5     */    public static Integer valueOf(int i) {        if (i >= IntegerCache.low && i <= IntegerCache.high)            return IntegerCache.cache[i + (-IntegerCache.low)];        return new Integer(i);    }

The above Code indicates that there is a range when the box is automatically disassembled. Once the range is exceeded, it is not pointed to the same object, instead, a newly created object is returned. This range can be reflected in an internal private class IntegerCache In the Integer class. The source code is as follows:

 private static class IntegerCache {        static final int low = -128;        static final int high;        static final Integer cache[];        static {            // high value may be configured by property            int h = 127;            String integerCacheHighPropValue =                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");            if (integerCacheHighPropValue != null) {                try {                    int i = parseInt(integerCacheHighPropValue);                    i = Math.max(i, 127);                    // Maximum array size is Integer.MAX_VALUE                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);                } catch( NumberFormatException nfe) {                    // If the property cannot be parsed into an int, ignore it.                }            }            high = h;            cache = new Integer[(high - low) + 1];            int j = low;            for(int k = 0; k < cache.length; k++)                cache[k] = new Integer(j++);            // range [-128, 127] must be interned (JLS7 5.1.7)            assert IntegerCache.high >= 127;        }        private IntegerCache() {}    }

The value range is [-128,127.

Note:The implementation of valueOf methods for Integer, Short, Byte, Character, and Long classes is similar.
The implementation of the valueOf Method of Double and Float is similar.

Summary: The scope of these basic types of Automatic Disassembly boxes is as follows:

1. boolean type value

2. All byte values

3. In-128 ~ Short value of 127

4. Go to-128 ~ Int value of 127

5. In \ u0000 ~ Char type value between \ u00ff

Here, double and float are different. We use double as an example to describe the Code:

Package com. ygh. CZX; /*** Analysis of java disassembly box scope ** @ author night lone cold * @ version 1.1.1 */public class Test {/*** Double */public static void first () {Double i1 = 100.0; Double i2 = 100.0; Double i3 = 200.0; Double i4 = 200.0; System. out. println (i1 = i2); // false System. out. println (i3 = i4); // false}/*** Test Method */public static void main (String [] args) {first ();}}

Note: Why is the output result of the above Code false? Similarly, we still discuss it with the valueOf method in the Double class, so we can see it at a glance after we paste the source code:

    /**     * Returns a {@code Double} instance representing the specified     * {@code double} value.     * If a new {@code Double} instance is not required, this method     * should generally be used in preference to the constructor     * {@link #Double(double)}, as this method is likely to yield     * significantly better space and time performance by caching     * frequently requested values.     *     * @param  d a double value.     * @return a {@code Double} instance representing {@code d}.     * @since  1.5     */    public static Double valueOf(double d) {        return new Double(d);    }

That is to say, no matter what the value of your double is, it returns a new object to you. Float is the same as double.

The above is some of my work on the disassembly box. If you have different opinions, you can submit them in the comment area and I will modify them again!

Related Article

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.