In-depth understanding of automatic boxing and unboxing in java
1. What is boxing and what is unboxing
Boxing: Convert basic data types into packaging classes.
Unboxing: Convert the wrapper class into a basic data type.
The packaging class corresponding to the basic data type:
int (a few bytes 4) - Integer
byte (1) - Byte
short (2) - Short
long (8) - Long
float (4) - Float
double (8) - Double
char (2 ) - Character
boolean (undefined) - Boolean
Free online video learning tutorial recommendation: java video tutorial
2. First Let’s take a look at manual boxing and manual unboxing
Example: Take int and Integer as examples
Integer i1=Integer.valueOf(3); int i2=i1.intValue();
Manual boxing is done through valueOf. Everyone knows that = assigns the right value to On the left, 3 is of type int. When assigned to the left, it becomes an Integer wrapper class.
Manual unboxing is done through intValue(). You can see through the code that i1 changes from Integer to int
3. After reading it manually, let’s look at the automatic
In order to ease the work of technical personnel, Java has changed from jdk1.5 to automatic boxing and unboxing. Take the above example:
Manual:
Integer i1=Integer.valueOf(3); int i2=i1.intValue();
Automatic
Integer i1=3; int i2=i1;
This is automatically installed and disassembled by default.
4. Deepen your understanding of automatic boxing and unboxing from several questions
(1)
Integer a = 100; int b = 100; System.out.println(a==b);结果为 true
Reason: a will automatically Unboxing and comparing with b, so it is true
(2)
Integer a = 100; Integer b = 100; System.out.println(a==b);//结果为true Integer a = 200; Integer b = 200; System.out.println(a==b);//结果为false
An interesting thing happened, why are the two variables the same, only the one with different values is true , one is false.
Reason: In this case, we need to talk about the comparison symbol ==. The memory address of == comparison is the memory address of the object that comes out of new. When you see this, you may ask that there seems to be no new. Ah, but actually Integer a=200; 200 is preceded by new Integer by default, and the memory address used is different == The comparison is false, but why is 100 true? This is because of the constant pool in java. We can click on the source code of Integer to take a look.
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; }
When comparing between -128 and 127, the new object will not be new, but will be obtained directly from the constant pool, so 100 is true, 200 exceeds this range and then a new operation is performed. , so the memory addresses are different.
(3)
Integer a = new Integer(100); Integer b = 100; System.out.println(a==b); //结果为false
This is similar to the 100 above. Take it from the constant pool. Why is it false?
Reason: The reason for new Integer(100). Although 100 can be taken from the constant pool, you cannot directly give new an object. The two memory addresses used are different.
(4)
Integer a = 100; Integer b= 100; System.out.println(a == b); //结果true a = 200; b = 200; System.out.println(c == d); //结果为false
Reason: The value on the right side of = sign is assigned to a on the left, b is already a packaging class, 200 is not in the constant pool, assign the int type 200 to the packaging class, automatically Because the boxing is not in the constant pool, the object is new by default, so the result is false.
For more related articles and tutorials, you can visit: Java language introduction
The above is the detailed content of In-depth understanding of automatic boxing and unboxing in java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

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

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

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

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
