Java Reference
In-Depth Information
public
public class
class
AutoboxDemo
AutoboxDemo
{
/** Shows autoboxing (in the call to foo(i), i is wrapped automatically)
* and auto-unboxing (the return value is automatically unwrapped).
*/
public
public static
static
void
void
main
(
String
[]
args
) {
int
int
i
=
42
;
int
int
result
=
foo
(
i
);
System
.
out
.
println
(
result
);
}
public
public static
static
Integer
foo
(
Integer i
) {
System
.
out
.
println
(
"Object = "
+
i
);
return
return
Integer
.
valueOf
(
123
);
}
}
Autoboxing:
int 42
is converted to
Integer(42)
. Also auto-unboxing: the
Integer
re-
turned from
foo()
is auto-unboxed to assign to
int result
.
No Auto-boxing:
valueOf()
returns
Integer
. If the line said
return In-
teger.intValueOf(123)
then it would be a second example of auto-boxing because the
method return value is
Integer
.
To explicitly convert between an
int
and an
Integer
object, or vice versa, you can use the
wrapper
class methods:
public
public class
class
IntObject
IntObject
{
public
public static
void
main
(
String
[]
args
) {
// int to Integer
Integer i1
=
Integer
.
valueOf
(
42
);
System
.
out
.
println
(
i1
.
toString
());
static
void
// or just i1
// Integer to int
int
int
i2
=
i1
.
intValue
();
System
.
out
.
println
(
i2
);
}
}