Home

autoboxing

Autoboxing is the automatic conversion between primitive types and their corresponding object wrapper classes by the compiler or runtime. In languages such as Java, these conversions allow primitive values to be used where objects are required, and conversely enable objects to be treated as primitives in certain contexts. For Java, the common pairs are int with Integer, long with Long, boolean with Boolean, char with Character, byte with Byte, short with Short, float with Float, and double with Double. Unboxing is the reverse process.

In Java, autoboxing is implemented by the compiler and can involve calls to valueOf for boxing and

In C#, boxing and unboxing apply when a value type is treated as an object or as

Common issues include null values and reference equality. Unboxing a null reference in Java yields a NullPointerException,

unboxing
operations
for
converting
back
to
primitives.
This
feature
is
essential
for
using
primitives
in
generic
types
and
collections,
such
as
List<Integer>,
where
type
parameters
must
be
reference
types.
Java
also
implements
caching
for
frequently
used
values
(for
example,
Integer.valueOf(-128)
to
valueOf(127)
are
cached),
which
reduces
the
cost
of
boxing
in
common
cases.
an
interface
type.
Boxing
wraps
the
value
in
a
reference-type
object
on
the
heap,
while
unboxing
extracts
the
value
through
a
type
cast.
Boxing
is
necessary
for
non-generic
collections
and
for
interoperability
with
APIs
that
expect
objects,
but
it
incurs
allocation
and
later
garbage
collection
overhead.
Unboxing
requires
an
explicit
or
implicit
cast
and
can
fail
at
runtime
if
the
value
is
not
of
the
expected
type.
and
comparing
wrapper
objects
with
==
may
compare
references
rather
than
values.
Performance-wise,
unnecessary
boxing
can
add
overhead;
in
performance-critical
code,
it
is
often
preferable
to
minimize
boxing
or
to
use
primitive-focused
facilities
where
available.