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?
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).
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With