Read what is automatic unboxing in Java

Source: Internet
Author: User
Tags character classes wrapper java se

Basic data types

A primitive type, or a built-in type, is a special type that differs from the class in Java. They are the most frequently used types in our programming.

Java is a strongly typed language, and the first declaration of a variable must describe the data type, and the first variable assignment is called the initialization of the variable.

There are eight basic types of Java, the basic types can be divided into three categories:

    • Character type Char
    • BOOL Type Boolean
    • Integer type Byte, short, int, long
    • Floating-point number type float, double.

There are no unsigned numeric types in Java, and their range is fixed and will not change with the machine hardware environment or the operating system.

In fact, there is another primitive type Void in Java, which also has a corresponding wrapper class java.lang.Void, but we cannot manipulate them directly.

What are the benefits of a basic data type?

We all know that in the Java language, the new object is stored in the heap, and we use those objects through references in the stack, so the object itself is more resource-intensive.

For frequently used types, such as int, if we need new Java objects every time we use this variable, it will be cumbersome.

So, like C + +, Java provides basic data types, which do not need to be created with new, they are not created on the heap, they are stored directly in the stack memory, and therefore are more efficient.

Range of values for integral types

The integer type in Java mainly contains four kinds of byte, short, int, and long, representing the range of numbers is also small to large, the reason that the range is different is mainly related to the number of bytes they are storing data.

First, a simple answer to the science, 1 bytes = 8 bit (bit). An integral type in Java is a signed number.

Let's look at the numbers that 8bit can represent in the calculation:

Minimum value: 10000000 ( -128) ( -2^7) maximum value:

Of these types of integral type,

    • The byte:byte is stored in 1 bytes with a range of-128 ( -2^7) to 127 (2^7-1), and the default value for the byte type is 0 when the variable is initialized.
    • The short:short is stored in 2 bytes, ranging from 32,768 ( -2^15) to 32,767 (2^15-1), when the variable is initialized, the default value for the short type is 0, and generally, because the Java itself transforms, it can be directly written as 0.
    • The int:int is stored in 4 bytes with a range of-2,147,483,648 ( -2^31) to 2,147,483,647 (2^31-1), and the default value for the int type is 0 when the variable is initialized.
    • The Long:long is stored in 8 bytes with a range of-9,223,372,036,854,775,808 ( -2^63) to 9,223,372,036, 854,775,807 (2^63-1), and when the variable is initialized, The default value for the long type is 0L or 0l, or it can be written directly as 0.

What about out of range

As mentioned above, each type has a certain range of representations in the integer, but some calculations in the program result in exceeding the presentation range, which is overflow. such as the following code:

int i =int j = Integer.max_value;   int k = i + j; System.out.println (

Output: I (2147483647) + j (2147483647) = K (-2)

This is when an overflow occurs, the overflow does not throw an exception, and there is no hint. Therefore, in the program, the use of the same type of data for the operation, it is important to pay attention to the problem of data overflow.

Package Type

The Java language is an object-oriented language, but the basic data types in Java are not object-oriented, which in the actual use of a lot of inconvenience, in order to solve this shortcoming, in the design of the class for each basic data type to design a corresponding class to represent, The classes that correspond to the eight basic data types are collectively referred to as wrapper classes (Wrapper Class).

The wrapper classes are located in the Java.lang package, and the corresponding relationship between the wrapper class and the base data type is shown in the following table

In these eight class names, in addition to the integer and character classes, the class names and basic data types of the other six classes are identical, except for the first letter of the class name.

Why packaging classes are required

A lot of people will wonder, since there are eight basic data types available in Java to improve efficiency, why should we provide packaging classes?

This question, in fact, already has the answer, because Java is an object-oriented language, many places need to use objects rather than basic data types. For example, in a collection class, we cannot put int, double, and so on. Because the container of the collection requires that the element be of type object.

In order for the base type to have the characteristics of an object, the wrapper type, which is equivalent to "wrapping" the base type, makes it a property of the object and adds properties and methods to it, enriching the operation of the primitive type.

Unpacking and Packing

So, with the basic data types and wrapper classes, there must be some time to convert between them. For example, an int that converts a primitive data type to an integer object of a wrapper type.

We think that the packaging class is the basic type of packaging, so, the basic data type conversion to packaging class process is to play packaging, English corresponds to boxing, Chinese translation for boxing.

Conversely, the process of converting a wrapper class into a basic data type is unpacking, and the English language corresponds to unboxing, and the Chinese translation is unboxing.

Before the Java SE5, to be boxed, you can use the following code:

New

Automatic unpacking and Automatic packing

In Java SE5, in order to reduce the developer's work, Java provides automatic unpacking and auto-boxing capabilities.

Automatic Boxing: The basic data type is automatically converted to the corresponding wrapper class.

Automatic unpacking: The wrapper class is automatically converted to the corresponding basic data type.

Integer i =10;  //  int b= i;     //

The integer i=10 can replace the integer i = new Integer (10), which is because Java provides automatic boxing, without the need for the developer to manually go to the new integer object.

The principle of automatic box packing and automatic unpacking

Now that Java provides the ability to disassemble the box, let's take a look at what the principle is, and how Java is implemented as an automatic unboxing feature.

We have the following code for the Automatic disassembly box:

 Public Static  void Main (String[]args) {     integer integer//    int//

After you decompile the above code, you can get the following code:

 Public Static  void Main (String[]args) {     integer integer=integer.valueof (1);       int i=integer.intvalue ();  

From the above anti-compiled code can be seen that the automatic packing of int is through the integer.valueof () method to achieve, integer automatic unpacking is achieved through the integer.intvalue. If the reader is interested, you can try to decompile all eight types, and you will find the following rules:

Automatic boxing is achieved through the valueof () method of the wrapper class. Automatic unpacking is done by wrapping the Xxxvalue () of the class object.

Which places are automatically boxed

After we've seen the fundamentals, we'll look at what happens when Java helps us with our automated unpacking. The initialization and assignment of variables mentioned earlier is not described, which is the simplest and easiest to understand.

Let's take a look at the scenarios that might be overlooked.

Scenario one, putting the basic data type into the collection class

We know that the collection class in Java can only receive object types, then why does the following code not error?

New arraylist<> for (int i = 1; i <; i + +) {     

To decompile the above code, you can get the following code:

New arraylist<> for (int i = 1; i <; i + = 2) {     

Above, we can conclude that when we put the basic data type into the collection class, it is automatically boxed.

Scenario two, the size comparison of the package type and the basic type

Has anyone ever thought about what it actually compares when we compare the size of an integer object to the base type? Look at the following code:

Integer a=1; System.out.println (a==1? ") equals ":" Not Equal to "); Boolean bool=false; SYSTEM.OUT.PRINTLN (BOOL

To decompile the above code, get the following code:

Integer a=1; System.out.println (A.intvalue ()==1? " equals ":" Not Equal to "); Boolean bool=false; System.out.println (Bool.booleanvalue

As you can see, the wrapper class is compared with the basic data type by unpacking the wrapper class into the basic data type first.

Scenario three, the operation of the packing type

Has anyone ever thought about how we did it when we arithmetic the integer object? Look at the following code:

Integer i = ten=; System.out.println (i

The post-compilation code is as follows:

Integer i = integer.valueof (ten= integer.valueof (20

We found that the operations between the two package types would be automatically disassembled into the basic type.

Use of the scenario four or three mesh operator

This is a scenario many people do not know, and the author is also a case of a bloody bug on the line after the occurrence. Look at the code for a simple three-mesh operator:

Boolean true  = 0int j = 1int

A lot of people don't know, actually in int k = flag? I:j; In this line, the automatic unpacking will occur. The post-compilation code is as follows:

Boolean true  = integer.valueof (0int j = 1int

This is actually the syntax specification for the trinocular operator: when the second, third-digit operand is a primitive type and an object, the objects in it will be disassembled to operate as the base type.

Because of the example, flag? I:j; In the fragment, the second paragraph of I is an object of the wrapper type, and the third paragraph of j is a basic type, so the wrapper class is automatically disassembled. If the value of I at this time is null, then the NPE will occur for a long time. (Automatic unpacking causes null pointer exceptions)

Scenario five, function parameters and return values

This is relatively easy to understand, directly on the code:

    public int getNum1 (Integer num) {return//   Public Integer getNum2 (int  num) {  return  

Automatic unboxing and caching

The automatic unboxing of Java SE also provides a cache-related feature, so let's take a look at the following code and guess the output:

 Public Static voidMain (String ... strings) {Integer Integer1= 3; Integer Integer2= 3; if(Integer1 = =integer2) System.out.println ("Integer1 = = Integer2"); ElseSystem.out.println ("Integer1! = Integer2"); Integer Integer3= 300; Integer Integer4= 300; if(Integer3 = =integer4) System.out.println ("Integer3 = = Integer4"); ElseSystem.out.println ("Integer3! = integer4"); } 

We generally believe that the result of the above two judgments is false. Although the comparison values are equal, the two if judgments are considered false because the objects are compared and the references to the objects are different.

in Java, = = Compares an object application, while equals compares a value.

So, in this case, different objects have different references, so the comparison will return false. Oddly, here are two similar if conditions that determine the return of different Boolean values.

The actual output of the above code is:

Integer1 = =

The reason is related to the caching mechanism in integer. In Java 5, a new feature was introduced on the operation of Integer to save memory and improve performance. An integer object implements caching and reuse by using the same object reference.

Applies to integer values range-128 to +127.

Applies to automatic boxing only. Creating objects using constructors does not apply.

The specific code implementation can read the cache mechanism of integer in Java, which is not elaborated here.

We just need to know that when auto boxing is required, if the number is between 128 and 127, the objects in the cache are used directly instead of recreating an object.

The Javadoc detailed description of the cache support-the automatic boxing process between 128 and 127. The maximum value of 127 can be modified by-xx:autoboxcachemax=size.

In fact, this feature was introduced in Java 5 with a fixed range of 128 to +127. Later in Java 6, you can set the maximum value by Java.lang.Integer.IntegerCache.high.

This allows us to flexibly adapt to the actual application to improve performance. What is the reason for choosing this-128 to 127 range? Because the number of this range is the most widely used. In a program, the first time an integer is used, it also takes some extra time to initialize the cache.

The Java Language Specification (JLS) in the Boxing conversion section provides the following:

If the value of a variable p is:

-Integers between 128 and 127 (§3.10.1)  true and False for Boolean values (§3.10.3)  ' \u0000 ' to ' \u007f ' characters (§

In the range, when p is packaged as a and B two objects, you can use A==B to determine whether the values of a and B are equal.

Problems with automatic unboxing

Of course, automatic unboxing is a great feature that saves the developer's energy and no longer needs to be concerned about when it needs to be unboxing. However, he will also introduce some problems.

The value of the wrapper object is not simple to use = =, although the number between 128 and 127 can be, but this range still need to use equals comparison.

As mentioned earlier, some scenes will be automatically disassembled, but also said that, because of the automatic unpacking, if the wrapper class object is null, then the automatic unpacking will be possible to throw the NPE.

If there is a large number of unboxing operations in a for loop, many resources are wasted.

Read what is automatic unboxing in Java

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.