Home > Java > javaTutorial > A brief introduction to automatic unboxing in Java

A brief introduction to automatic unboxing in Java

黄舟
Release: 2017-10-12 10:15:22
Original
1245 people have browsed it

This article mainly introduces the relevant information of Java automatic unboxing in detail, which has certain reference value. Interested friends can refer to it

During the interview process, there are often questions When the interviewer asks basic questions, he will always ask about Java unpacking. This question is actually not difficult, but if you don’t pay attention during self-study, you may be confused, so the author will do some research on this question. Summary, let’s promote together!

1. The concept of unboxing

The so-called unboxing is the difference between java’s basic types and reference types since JDK1.5. Convert each other.

1.1 Unboxing

Unboxing is the action of converting Long, Integer, Double, Float and other corresponding reference types with the first letter of the basic data type capitalized into basic data types. It is called unboxing. box.

1.2 Boxing

Boxing means byte, int, short, long, double, float, boolean, char. These Java basic data types are not declared as corresponding when defining the data type. The action of automatically converting a reference type into a reference type under the processing of the compiler is called boxing.

2. Related applications of unboxing

After JDK1.5, it will be convenient when we convert basic types and reference types :


package com.hzp.CZX;
/**
 * 测试拆装箱
 * @author 夜孤寒
 * @version 1.1.1
 */
public class TestDemo {
  /**
   * 拆装箱JDK1.5后
   */
  public static void first(){
    Integer i=7;//基本类型-->引用类型
    int j=i;//引用类型-->基本类型
    System.out.println(j);
  }
  /**
   * 拆装箱JDK1.4
   */
  public static void second(){
    Integer i=new Integer(78);
    int j=i.intValue();
    System.out.println(j);
  }
  /**
   * 测试方法
   * @param args
   */
  public static void main(String[] args) {
    first();
    second();
  }
}
Copy after login

The above introduces some basic points and usage methods about the disassembly box, but there are some points that need to be paid attention to when using the disassembly box. These are listed below. Pay attention to some summary.

3. Notes

First post a piece of code as follows:


package com.ygh.CZX;
/**
 * 关于java的拆装箱范围剖析
 * @author 夜孤寒
 * @version 1.1.1
 */
public class Test {
  /**
   * 以Integer类型为例
   */
  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();
    
  }
}
Copy after login

A brief explanation :

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

But why are the results of the second and third different?

The source code for the Integer class is posted below to analyze this problem 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);
  }
Copy after login

The above code means to perform automatic disassembly and assembly When boxing, there is a range. Once it exceeds this range, it will not point to the same object, but will return a newly created object. This range can be reflected in IntegerCache, an internal private class 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() {}
  }
Copy after login

From here we can see that the range value is between [-128,127].

Note that the implementation of the valueOf method of Integer, Short, Byte, Character, and Long classes are similar.
The implementation of the valueOf method of Double and Float is similar.

Summary: The range of these basic types for automatic unboxing is as follows:

1. boolean type value

2. All byte values

3. Short type value between -128~127

4. Int type value between -128~127

5.Char between \u0000~\u00ff The type of value

And double and float are different. Let’s take double as an example and post the code discussion:


package com.ygh.CZX;

/**
 * 关于java的拆装箱范围剖析
 * 
 * @author 夜孤寒
 * @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
  }
  /**
   * 测试方法
   */
  public static void main(String[] args) {
    first();
  }
}
Copy after login

Pay attention to why the above The output results of the code are all false? Similarly, we still use the valueOf method in the Double class to discuss. Posting the source code will make it clear at a glance:


  /**
   * 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);
  }
Copy after login

That is to say, no matter what range of values ​​your double is, He always returns a new object to you. float is the same as double, so I won’t go into details.

The above is the author's arrangement of the unpacking box. If readers have different opinions, they can put them forward in the comment area, and the author will make modifications!

The above is the detailed content of A brief introduction to automatic unboxing in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template