search
HomeJavajavaTutorialA brief introduction to automatic unboxing in Java

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();
  }
}

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();
    
  }
}

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);
  }

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() {}
  }

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();
  }
}

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);
  }

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!

Statement
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
Why does the browser fail to correctly process the 401 status code when developing a WebSocket server using Netty?Why does the browser fail to correctly process the 401 status code when developing a WebSocket server using Netty?Apr 19, 2025 pm 07:21 PM

在使用Netty开发WebSocket服务器时,可能会遇到浏览器在尝试连接时未能正确处理服务器返回的401状态码的情况。 �...

Java compilation failed: What should I do if the javac command cannot generate the class file?Java compilation failed: What should I do if the javac command cannot generate the class file?Apr 19, 2025 pm 07:18 PM

Java compilation failed: Running window javac command cannot generate class file Many Java beginners will encounter this problem during the learning process: running window...

How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development?How to correctly divide business logic and non-business logic in hierarchical architecture in back-end development?Apr 19, 2025 pm 07:15 PM

Discussing the hierarchical architecture problem in back-end development. In back-end development, common hierarchical architectures include controller, service and dao...

Java compilation error: How do package declaration and access permissions change after moving the class file?Java compilation error: How do package declaration and access permissions change after moving the class file?Apr 19, 2025 pm 07:12 PM

Packages and Directories in Java: The logic behind compiler errors In Java development, you often encounter problems with packages and directories. This article will explore Java in depth...

Is JWT suitable for dynamic permission change scenarios?Is JWT suitable for dynamic permission change scenarios?Apr 19, 2025 pm 07:06 PM

JWT and Session Choice: Tradeoffs under Dynamic Permission Changes Many Beginners on JWT and Session...

How to properly configure apple-app-site-association file in pagoda nginx to avoid 404 errors?How to properly configure apple-app-site-association file in pagoda nginx to avoid 404 errors?Apr 19, 2025 pm 07:03 PM

How to correctly configure apple-app-site-association file in Baota nginx? Recently, the company's iOS department sent an apple-app-site-association file and...

What are the differences in the classification and implementation methods of the two consistency consensus algorithms?What are the differences in the classification and implementation methods of the two consistency consensus algorithms?Apr 19, 2025 pm 07:00 PM

How to understand the classification and implementation methods of two consistency consensus algorithms? At the protocol level, there has been no new members in the selection of consistency algorithms for many years. ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.