Table of Contents
1. Preface
2. Packaging class
3. Automatic boxing and automatic unboxing
4. Interger cache
5. Answer the question
Home Java javaTutorial How to use Java automatic boxing, automatic unboxing and Integer caching

How to use Java automatic boxing, automatic unboxing and Integer caching

Apr 24, 2023 pm 10:28 PM
java integer

1. Preface

What are automatic boxing and automatic unboxing? What is Integer cache? What's the relationship between them?

Let’s look at a question first.

Integer a = new Integer(1);
Integer b = new Integer(1);
System.out.println(a==b);
Integer c = 1;
Integer d = 1;
System.out.println(c==d);
Integer e = 128;
Integer f = 128;
System.out.println(e==f);
Copy after login
Copy after login

Answer first, look at the answer later.

The answer is false true false, are you correct?

Now that one piece has appeared, let’s share the knowledge points together

2. Packaging class

There are eight basic data types in Java, which can be divided into three categories:

  • Character type: char

  • Boolean type: boolean

  • Numeric type: byte short int long float double

Packaging classes wrap eight basic data types into classes so that they can use Java's three major features: encapsulation, inheritance, and polymorphism. The corresponding relationship is as follows:

Basic data typeCorresponding packaging class
byteByte
shortShort
intInteger
#longLong
float#Float
doubleDouble
booleanBoolean
charCharacter

The six packaging classes corresponding to numerical types all inherit from the Number class.

3. Automatic boxing and automatic unboxing

The eight basic data types correspond to the eight packaging classes, so how do they perform data conversion?

//基本数据类型转包装类
//1.有参构造
Integer a = new Integer(1);
//2.实际上,有参构造的参数也可以是字符串,不过要使用正确的数据,“123abc”不可能会转换为Integer类型
Integer b = new Integer("123");
//3.valueOf()
Integer c = Integer.valueOf(123);
//包装类转基本数据类型(xxxValue()  float是floatValue() double是doubleValue())
int d = a.intValue();
Copy after login

The above forms are relatively consistent with cognition. To obtain an object, you can use new or call a certain method. To obtain a value, call a certain attribute of the object.

After Java 5.0, you don’t have to be so troublesome. New features of automatic boxing and automatic unboxing have been added. In fact, the two concepts are very easy to understand.

int a = 10;
Integer b = a;  //自动装箱
int c = b;  //自动拆箱
Copy after login

At first glance, the form of object=numeric value does not conform to cognition, but it can be achieved with the help of automatic boxing and automatic unboxing. In fact, the compiler still implements it with the help of valueOf() and xxxValue().

Let’s take a look at the valueOf() source code.

/**
     * 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

valueOf() does not simply return an Integer object, but first makes a judgment. If the input data matches a certain range, it will return a specific object. From the comments, this range The default is [-128,127], and may be a larger range; beyond this range, a new object will be returned. The IntegerCache data used is the cache of Integer.

4. Interger cache

Numerical calculations are used frequently in daily life. If you keep getting new Integer objects, the overhead will be very large. Therefore, Java will automatically generate a new Integer object when executing the program. Static arrays are used as caches. The default cache array range corresponding to Integer is [-128,127]. As long as the data is within this range, the corresponding object can be obtained from the cache.

Look at the IntegerCache source code.

/**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=<size>} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */
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

As you can see, IntegerCache is a static internal class of Integer. IntegerCache.cache called by valueOf() is an array object. The size of the array depends on the maximum and minimum values ​​in the range. The default is [- 128, 127], of course (the comment says) this range can also be modified through the JVM (I don't understand this). Then each element in the array will be assigned an Integer object, and the cache will be formed.

There is an array cache, which means that if the value is in [-128,127], the Integer object created using valueOf() or automatic boxing is taken out from the array, so the memory address pointed to by the object is exactly the same. If you use new or exceed this range, the object must be re-created.

Of course, not only Integer has a caching mechanism, Byte, Short, Long, and Character all have caching mechanisms. The range of Byte, Short, Integer and Long is -128 to 127, and the range of Character is 0 to 127.

5. Answer the question

Integer a = new Integer(1);
Integer b = new Integer(1);
System.out.println(a==b);
Integer c = 1;
Integer d = 1;
System.out.println(c==d);
Integer e = 128;
Integer f = 128;
System.out.println(e==f);
Copy after login
Copy after login

1. Even if the two objects created by new have the same value, they point to different memory addresses. Using == for comparison returns a false

2. Automatic boxing and caching mechanism. The two objects are actually the same and the return result is true

3. Beyond the cache range, a new object will be new during execution. If the two objects are different, return The result is false

The above is the detailed content of How to use Java automatic boxing, automatic unboxing and Integer caching. For more information, please follow other related articles on the PHP Chinese website!

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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles