JAVA unpacking boxes

Reprinted from: micro-channel public numberWeb project gathering

Basic data types

  The basic type, or called built-in type, different from a Java class (Class) of special type. They are our programming most frequently used type.

  Java is a strongly typed language, first declared variable data types must be stated, first called variable assignment to initialize variables.

 

Java primitive types There are eight basic types can be divided into three categories:

  Character Types char

  Boolean boolean

  Integer type  byte, short, int,long

  Floating-point type  float, double.

Java numeric type does not exist unsigned, their range is fixed, as the machine does not change the operating system or hardware environment is changed.

In fact, Java, there are still another basic type void, it also has a corresponding wrapper class , but we can not operate on them directly. java.lang.Void

What are the benefits of basic data types

  We all know that in the Java language, newan object is stored in a heap, we use these objects by reference stack; therefore, it is the object itself is resource consuming.

  For the type frequently used, such as int, etc. If every time we use this variable will require a new Java object, then, it will be rather cumbersome.

  Therefore, and as C ++, Java provides the basic data types, variables such data does not require the use of new creation, they will not be created on the heap, but is stored directly in the stack memory, so it is more efficient.

 

The range of integer

  Java, integer mainly include byte, short, intand longfour digital range indicated is from small to large, represent a range of different main reason why the number of bytes occupied and when they store data related.

  First to a short-answer science, 1 byte = 8 bits (bit). java belong to the integer number of symbols.

  First look in 8bit digital calculation can be represented by:

  最小值:10000000 (-128)(-2^7)最大值:01111111(127)(2^7-1)

  These integer types,

  • byte: byte by one byte to store, in the range of -128 (7 ^ -2) to 127 (2 ^ 7-1), when initialized variable, byte 0 is the default type.

  • short: short with 2 bytes of storage, -32,768 (-2 ^ 15) to 32,767 (2 ^ 15-1), when initialized variable, short type default value 0, in general, because the Java the reason for the transition itself can be directly written to zero.

  • int: int 4 bytes is stored, in the range of 2,147,483,648 (-2 ^ 31) to 2,147,483,647 (2 ^ 31-1), when initialized variable, int type default value 0.

  • long: long with 8 bytes of storage, -9,223,372,036,854,775,808 range (-2 ^ 63) to 9,223,372,036, 854,775,807 (2 63 -1), when initialized variable, long type or 0L 0L default value, may also be write directly to zero.

  • byte short char int long float double 1 2 2 4 8 4 8 

 

Beyond the scope of how to do

  The above said, integers, each type has a certain range of representation, however, some calculation in the program will result in exceeding the scope of representation, namely overflow. As the following code:

  int i = Integer.MAX_VALUE;int j = Integer.MAX_VALUE;
  int k = i + j;System.out.println("i (" + i + ") + j (" + j + ") = k (" + k + ")");

  Output: i (2147483647) + j (2147483647) = k (-2)

  This is what has happened overflow, time and does not throw an exception, and without any prompting. So, when in the program, using the same type of data operations, we must pay attention to the problem of data overflow.

 

Wrapper class

Java is an object-oriented language, but the basic data types in Java is not an object-oriented, which there are many inconveniences in actual use, in order to solve this problem, in the design category for each data type basic design It is representative of a corresponding class, so that eight basic data types and corresponding class referred to as packaging (wrapper class).

Java.lang package are located packaging, packaging of basic data types and the corresponding relationship table below

Basic data types Wrapper class
byte Byte
boolean Boolean
short Short
char Character
int Integer
long Long
float Float
double Double

In the eight class name, in addition to the future Integer and Character type, the same class of six other class name and basic data types, only the first letter of the class name to uppercase.

Why do we need packaging

Many people have doubts, since Java in order to improve efficiency, it offers eight basic data types, why should we provide packaging it?

The problem, in fact, already been answered, because Java is an object-oriented language, many places need to use objects instead of primitive data types. For example, in the collections, we are unable to int, double, etc. type into them. Because the container element is set in claim Object type.

To make basic types also have a feature object, appeared package type, which corresponds to the fundamental type "wrap up", so that it has the property of the object, and to add properties and methods to enrich the basic type of operation .

Packing and unpacking

So, with the basic data types and packaging, certainly there are times when you want to switch between them. For example converting a basic data type into a package type int Integer object.

We believe that packaging is the basic type of packaging, so the basic data type conversion process is playing into the wrapper class packaging, corresponding to the English boxing, the Chinese translation for boxing.

Conversely, to convert the packaging process of the base data is unpacked, Unboxing corresponding English, Chinese translation of unpacking.

Before Java SE5, to be packing, by the following code:

Integer i = new Integer(10);

Automatic and automatic packing unpacking

In Java SE5, in order to reduce the work of developers, Java provides automatic packing and unpacking automatic function.

Autoboxing: is automatically converted into a corresponding elementary data type packaging.

Automatic unboxing: wrapper is automatically converted to the corresponding basic data types.

Integer i =10;  //自动装箱int b= i;     //自动拆箱

Integer i=10 An alternative , which is to help us because Java provides automatic packing function does not require developers to manually a new Integer object. Integer i = new Integer(10);

The principle of auto-boxing and auto-unboxing

Now that Java provides the ability to automatically enables me, then we will look, in the end is what principle, Java is an automatic feature enables me how to achieve.

We have the following code for the automatic entry box:

public static  void main(String[]args)
{

Integer integer=1; //装箱

int i=integer; //拆箱

}

After the above code can be decompiled the following code:

public static  void main(String[]args)
{

Integer integer=Integer.valueOf(1);

int i=integer.intValue();

}

As can be seen above, decompiled code, int autoboxing is through Integer.valueOf()to achieve a method, Integer unboxing is through automatic integer.intValueachieved. If readers are interested, you can try the eight types are decompile it again, you will find the following rules:

By automatic packing wrapper classes are valueOf()implemented method for automatic unpacking of the class object by wrapping are xxxValue()achieved.

 

What place will automatically entry box

After we understood the principle, look, under what circumstances, Java will help us carry out automatic entry box. Initialization and assignment of scene variables mentioned above is not introduced, it is the simplest and most easily understood.

We mainly look at those scenarios may be ignored.

A scenario, the basic data types into collections

We know that, Java Collection classes can only receive an object type, then the following code why it is not being given?

List<Integer> li = new ArrayList<>();
for (int i = 1; i < 50; i ++)
{

li.add(i);
}

The above decompiled code, the following code can be obtained:

List<Integer> li = new ArrayList<>();

for (int i = 1; i < 50; i += 2)
{

li.add(Integer.valueOf(i));
}

Above, we can conclude that, when we put the basic data types into a collection class, it will automatically packing.

Second scenario, package type and size comparison of basic types

Has anyone ever thought, when we compare the size of the base type of Integer object, in fact, it is what to compare it? Look at the following code:

Integer a=1;System.out.println(a==1?"等于":"不等于");

Boolean bool=false;System.out.println(bool?"真":"假");

To decompile the code above, the following codes:

Integer a=1;System.out.println(a.intValue()==1?"等于":"不等于");

Boolean bool=false;System.out.println(bool.booleanValue?"真":"假");

It can be seen with the packaging operation basic data types are compared, it is the basic data types into a first packaging unpacking, and then compared.

Scenario three package types of operations

Has anyone thought about when we were four operations on Integer object, how is it? Look at the following code:

Integer i = 10;Integer j = 20;
System.out.println(i+j);

After the decompiled code is as follows:

Integer i = Integer.valueOf(10);Integer j = Integer.valueOf(20);System.out.println(i.intValue() + j.intValue());

We found that the type of packaging operation between the two, will be automatically unpack into basic types.

Scene four, using the ternary operator

This is what many people do not know of a scene a case after the bloody learned Bug author of a line occurs. See a simple ternary operator code:

boolean flag = true;Integer i = 0;int j = 1;int k = flag ? i : j;

Many people do not know, in fact, in int k = flag ? i : j;this line, auto-unboxing occur. After the decompiled code is as follows:

boolean flag = true;Integer i = Integer.valueOf(0);int j = 1;int k = flag ? i.intValue() : j;

This is actually a ternary operator syntax specification of: when the second and third operands are basic types and object, wherein the object will substantially unpacking operation type.

Because the example, flag ? i : j;segment, the second segment i is an object of a type of packaging, while the third stage j is a base type, the packaging will automatically unpacking. If this time i value null, so long NPE will occur.

Scene Five, function parameters and return values

This is easier to understand, directly on the code:

//自动拆箱public int getNum1(Integer num) { return num;}//自动装箱public Integer getNum2(int num) { return num;}

Automatic entry boxes and cache

Java SE automatic entry box and also provides a buffer-related functions, let's look at the following code, guess output:

public static void main(String... strings) {
Integer integer1 = 3;
Integer integer2 = 3;

if (integer1 == integer2)
System.out.println("integer1 == integer2");

else

System.out.println("integer1 != integer2");

Integer integer3 = 300;
Integer integer4 = 300;

if (integer3 == integer4)
System.out.println("integer3 == integer4");

else

System.out.println("integer3 != integer4");

}

We generally believe that the results of the above two judgments are false. Although the value of the comparison are equal, but because the comparison is an object, and the object references are not the same, so the two would think that if the judgments are false.

In Java, == comparison is the target application, and is the value equals comparisons.

So, in this example, different objects have different references, so when making comparisons will return false. Curiously, where two similar conditions if a different judgment returns a Boolean value.

The code above real output:

integer1 == integer2integer3 != integer4

The reason is in the cache and Integer mechanisms. In Java 5, on the operating Integer we introduce a new feature to save memory and improve performance. Integer object implements the cache and reuse by using the same object reference.

Apply to the entire value range -128 to +127.

 

Only suitable for automatic packing. Use constructor to create the object does not apply.

We just need to know when the need for automatic packing, if the number is between -128 to 127, will directly use objects in the cache, rather than re-create an object.

Wherein the detailed description of the cache javadoc support automatic packing process between -128 to 127. The maximum value of 127 can -XX:AutoBoxCacheMax=sizebe modified.

In fact this function when introduced in Java 5, a fixed range of -128 to +127. Later in Java 6, you can java.lang.Integer.IntegerCache.highset the maximum.

This allows us to improve the performance of the actual situation of the application the flexibility to adjust. In the end what is the reason to select the -128 to 127 range it? Because the numbers in this range is the most widely used.  In the process, the first use of Integer, also take some extra time to initialize the cache.

In the Java Language Specification (JLS) Boxing Conversion section provides as follows:

If a value of p variables are:

-128至127之间的整数(§3.10.1)
true 和 false的布尔值 (§3.10.3)
‘\u0000’至 ‘\u007f’之间的字符(§3.10.4)

When within range, the p-packaged two objects a and b, can be determined directly using a == b a and b are equal.

Question Box brings automatic dismantling

Of course, automatic entry box is a nice feature, saving energy developers no longer need to care about in the end when you need entry box. However, he also introduce some problems.

Numerical comparison wrapped object, can not simply use ==, although the number can be between -128 and 127, but outside this range still need to use equalsthe comparison.

 

As mentioned earlier, some scenes will be automatically enables me, but also said that due to the auto-unboxing, if the packaging class object is null, then it is possible to automatically throw NPE when unpacking.

 

If a loop for a large number of the entry box operation, will waste a lot of resources.

Guess you like

Origin www.cnblogs.com/heyjia/p/11328460.html