What are the data types supported by Java? When will the unpacking be automatically installed?

Source: Internet
Author: User
Tags float double

8 basic data Types in Java: boolean byte char short int float double long

The problem of the automatic disassembly box is introduced:

Because at the beginning of learning Java, "Everything is Object" This object-oriented way of looking at the problem, always around the mind. Because static variables and basic data types do not belong to an object, the automatic unpacking of 8 basic data types solves the basic data type not the object.

The new feature of the Automatic unpacking box was introduced in the jdk1.5, before jdk1.5 we wanted to use the method in the integer class, we first had to turn the int variable into an integer type, which could be passed the new integer (intnumber) or call the Integer.valueof (intnumber) method

When does automatic unpacking occur?

1. When invoking a method, the base data type is used as a parameter, but the type of the parameter is the wrapper class of the base data type.

After learning the basics of javase, we know that by using the set frame ArrayList or map to add elements, the object is added, and the source code for the Arraylist.add () is introduced here:

/**

* Appends the specified element to the end of this list.

*

* @param e element to being appended to the this list

* @return <tt>true</tt> (as specified by {@link Collection#add})

*/

Public boolean Add (E e) {

Ensurecapacity (size + 1); Increments modcount!!

elementdata[size++] = e;

return true;

}

1

2

3

4

5

6

7

8

9

10

11

The interpretation of the source code: First we look at the parameters of (e), why is E? Rather than object? Because E is the element (the element stored in the collection), we can usually see <t extends list<t>> in generics, T represents the type class, and then map<k,v>,k in the key-value pair represents key,v Represents the value. Generics such as E K V have already qualified the type before using this parameter, and if assigned to an object, no more coercion type conversions are necessary.

First put the length of the array +1, this operation will cause Modcount plus one, the function of this variable is to record the number of times the current array is manipulated, and then directly to the parameters passed in the object assigned to the last length position of the element. Returns true to indicate that the add succeeded

When we call the Arraylist.add () method, we can call directly

arraylist<integer> ArrayList = new arraylist<integer> ();

Arraylist.add (10);

1

2

We decompile this code:

public class Autoboxingtest

{

Public Autoboxingtest ()

{

}

public static void Main (String args[])

{

ArrayList ArrayList = new ArrayList ();

Arraylist.add (integer.valueof (100));

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

As you can see, the compiler detects that Arraylist.add () requires an integer object when compiling, so the int type is automatically boxed into an integer type.

2, the basic data type of the wrapper class is assigned to the basic data type when.

We also use variables of type integer and int as an example:

public class AutoboxingTest2 {

public static void Main (string[] args) {

Integer integer = 10;

}

}

1

2

3

4

5

6

7

Continue with the anti-compilation example:

public class AutoboxingTest2

{

Public AutoboxingTest2 ()

{

}

public static void Main (String args[])

{

Integer integer = integer.valueof (10);

}

}

1

2

3

4

5

6

7

8

9

10

11

12

When does automatic boxing not work?

When there is an overload in the method that we want to invoke, that is, the primitive type data as a method of the unique parameter is overloaded with the method of the basic type wrapper class as the only parameter, when auto boxing does not work.

Example:

public class Invalidateautoboxing {

public void print (int num) {

System.out.println ("I am int!");

}

public void print (Integer num) {

System.out.println ("I am integer!");

}

}

public class Invalidateautoboxingtest {

public static void Main (string[] args) {

invalidateautoboxing invalidateautoboxing = new invalidateautoboxing ();

Invalidateautoboxing.print (5);

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21st

Operation Result:

Write a picture description here

Places to note when using automatic boxing unpacking:

1, circulation and automatic packing and unpacking

public class Circulateandautoboxingandautounboxing {

public static void Main (string[] args) {

Integer sum = 0;

for (int i = 0; i <; i++) {

sum + = i;

}

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Anti-compilation:

public class Circulateandautoboxingandautounboxing

{

Public circulateandautoboxingandautounboxing ()

{

}

public static void Main (String args[])

{

Integer sum = integer.valueof (0);

for (int i = 0; i <; i++)

sum = integer.valueof (Sum.intvalue () + i);

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Decompile code interpretation: Since sum is an integer type, sum+=i requires sum to be automatically disassembled into an int type (called the Intvalue () method), added, and then automatically boxed into an integer type to assign the result to sum.

Integer.valueof Source Code Analysis:

/**

* Returns A Integer instance representing the specified

* int value.

* If A new Integer instance is no required, this method

* Should generally be used on preference to the constructor

* Integer (int), as this method was likely to yield

* Significantly better space and time performance by caching

* Frequently requested values.

*

* @param i an int value.

* @return a Integer instance representing I.

* @since 1.5

*/

public static Integer valueOf (int i) {

Final int offset = 128;

if (i >= -128 && i <= 127) {//must cache

return integercache.cache[i + offset];

}

return new Integer (i);

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

First we see in the source code that the constructor caches frequently used data to reduce memory usage and improve efficiency, integer sets the upper limit of the buffer to 128, if the data I pass in the -128~127, Directly returns elements from the Integercache.cache[i + 128] bit in the buffer

Integercache interpretation of the source code:

private Static Class Integercache {

Private Integercache () {}

Static final Integer cache[] = new integer[-(-128) + 127 + 1];

static {

for (int i = 0; i < cache.length; i++)

Cache[i] = new Integer (i-128);

}

}

1

2

3

4

5

6

7

8

9

10

Integercache is the inner class of integer, and the upper bound of the inner array is 256 elements, in which static blocks of code are used (only once when the class is loaded), and the -128~127 are in the array. Therefore, you can return the integer object immediately, without returning the new integer (i); The buffer array for the Integer short long is the same, but the character range is 0~127,double and float has no buffer array

Then again, we've just been analyzing the use of loops and automatic unpacking. Note that when the participating values are not in the cache, a large number of objects are generated, which creates a lot of garbage objects and increases the working pressure of the GC.

2. Null pointer exception (NPE) caused by automatic loading and unpacking and ternary operator

public class Autounboxingwithconditionaloperator {

public static void Main (string[] args) {

hashmap<string, boolean> HashMap = new hashmap<string, boolean> ();

Boolean B = (HashMap! = null? Hashmap.get ("Test"): false);

}

}

1

2

3

4

5

6

7

8

9

10

Run:

Write a picture description here

A null pointer exception has occurred

If you added the test data to the map:

public class Autounboxingwithconditionaloperator {

public static void Main (string[] args) {

hashmap<string, boolean> HashMap = new hashmap<string, boolean> ();

Hashmap.put ("Test", true);

Boolean B = (HashMap! = null? Hashmap.get ("Test"): false);

System.out.println (b);

}

}

1

2

3

4

5

6

7

8

9

10

Run:

Write a picture description here

We will then decompile the code for just the NPE exception:

public class Autounboxingwithconditionaloperator

{

Public Autounboxingwithconditionaloperator ()

{

}

public static void Main (String args[])

{

HashMap HashMap = new HashMap ();

Boolean B = boolean.valueof (HashMap = = null? False: ((Boolean) hashmap.get ("Test")). Booleanvalue ());

}

}

1

2

3

4

5

6

7

8

9

10

11

12

13

The following is a description of the Hashmap.get (key) method:

Returns the value to which the specified key is mapped,

*or NULL if this maps contains no mapping for the key.

As can be seen above, because of the map.get (key) method, if there is no data specified, NULL is returned.

Again because the ternary operator has the following definition:

The type of a conditional expression is determined as follows:

1. If the second and third operands has the same type (which may being the null type), then that is the type of the condition Al expression.

2, If one of the second and third operands is of the primitive type T, and the type of the the the the the the result of applying BOXI ng conversion (§5.1.7) to T, then the type of the conditional expression is T.

3, If one of the second and third operands is of the the null type and the type of the that the other is a reference type, then the type Of the conditional expression is this reference type.

President

The type of the ternary operator is determined by the following conditions:

1, if the second and third operation results have the same type (this type may be null), then this type is the result type of the ternary operator

2, if the second operation and the result of the third operation results type is the basic data type, another operation result can be boxed into a consistent with the previous type of wrapper class, then the operation result type of the ternary operator is the basic data type, that is, the packaging class disassembly.

3, if there is a null type in the second to third operation result, and the other is a reference type, then the expression of this ternary operator is a reference type.

In summary, for the above situation, for one operation result as the basic type, and another for the packing type of ternary operator expression, in order to avoid NEP, you can make it by turning them into the same type (refer to the first of the ternary operator definition).

Resources:

Conditional Operator? :

Boxing Conversion

The Java? Tutorials about autoboxing and unboxing

What's autoboxing and unboxing in Java

Automatic boxing and unpacking in Java

The box or the unpacking.

4.2 Self-installing box, unpacking

Java Automatic Boxing and unpacking

K-T V E in Java generics? Meaning of object, etc.

Automatic unpacking causes null pointer exception

What are the data types supported by Java? When will the unpacking be automatically installed?

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.