Java Reference
In-Depth Information
hold a single primitive value. These wrapper classes are usually used when you want
to store primitive values in collections such as java.util.List :
// Create a List collection
List numbers = new ArrayList ();
// Store a wrapped primitive
numbers . add ( new Integer (- 1 ));
// Extract the primitive value
int i = (( Integer ) numbers . get ( 0 )). intValue ();
Java allows types of conversions known as boxing and unboxing conversions. Box‐
ing conversions convert a primitive value to its corresponding wrapper object and
unboxing conversions do the opposite. You may explicitly specify a boxing or
unboxing conversion with a cast, but this is unnecessary, as these conversions are
automatically performed when you assign a value to a variable or pass a value to a
method. Furthermore, unboxing conversions are also automatic if you use a wrap‐
per object when a Java operator or statement expects a primitive value. Because Java
performs boxing and unboxing automatically, this language feature is often known
as autoboxing .
Here are some examples of automatic boxing and unboxing conversions:
Integer i = 0 ; // int literal 0 boxed to an Integer object
Number n = 0.0f ; // float literal boxed to Float and widened to Number
Integer i = 1 ; // this is a boxing conversion
int j = i ; // i is unboxed here
i ++; // i is unboxed, incremented, and then boxed up again
Integer k = i + 2 ; // i is unboxed and the sum is boxed up again
i = null ;
j = i ; // unboxing here throws a NullPointerException
Autoboxing makes dealing with collections much easier as well. Let's look at an
example that uses Java's generics (a language feature we'll meet properly in “Java
Generics” on page 142 ) that allows us to restrict what types can be put into lists and
other collections:
List < Integer > numbers = new ArrayList <>(); // Create a List of Integer
numbers . add (- 1 ); // Box int to Integer
int i = numbers . get ( 0 ); // Unbox Integer to int
Packages and the Java Namespace
A package is a named collection of classes, interfaces, and other reference types.
Packages serve to group related classes and define a namespace for the classes they
The core classes of the Java platform are in packages whose names begin with java .
For example, the most fundamental classes of the language are in the package
java.lang . Various utility classes are in java.util . Classes for input and output are
in , and classes for networking are in . Some of these packages
contain subpackages, such as java.lang.reflect and java.util.regex .
Search WWH ::

Custom Search