Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Autoboxing: So I can write: Integer i = 0; instead of: Integer i = new Integer(0);

Autoboxing seems to come down to the fact that I can write:

Integer i = 0; 

instead of:

Integer i = new Integer(0);

So, the compiler can automatically convert a primitive to an Object.

Is that the idea? Why is this important?

like image 611
Harry Quince Avatar asked Apr 20 '09 00:04

Harry Quince


People also ask

How do you create a new integer in Java?

To declare (create) a variable, you will specify the type, leave at least one space, then the name for the variable and end the line with a semicolon ( ; ). Java uses the keyword int for integer, double for a floating point number (a double precision number), and boolean for a Boolean value (true or false).

What is Autoboxing?

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

What is new integer in Java?

Integer class is a wrapper class for the primitive type int which contains several methods to effectively deal with an int value like converting it to a string representation, and vice-versa.

What is the major advantage of Autoboxing?

Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The technique lets us use primitive types and Wrapper class objects interchangeably and we do not need to perform any typecasting explicitly.


1 Answers

BTW

Integer i = 0;

is equivalent to

Integer i = Integer.valueOf(0);

The distinction is that valueOf() does not create a new object for values between -128 and 127 (Apparently this will be tunable if Java 6u14)

like image 79
Peter Lawrey Avatar answered Oct 11 '22 05:10

Peter Lawrey