Java Reference
In-Depth Information
In this example, objects of type
Double
hold values, which are then averaged and the result
assigned to another
Double
object. Although this code is technically correct and does, in
fact, work properly, it is a very bad use of autoboxing/unboxing. It is far less efficient than
the equivalent code written using the primitive type
double
. The reason is that each auto-
box and auto-unbox adds overhead that is not present if the primitive type is used.
In general, you should restrict your use of the type wrappers to only those cases in which
an object representation of a primitive type is required. Autoboxing/unboxing was not ad-
ded to Java as a “back door” way of eliminating the primitive types.
Static Import
Java supports an expanded use of the
import
keyword. By following
import
with the
keyword
static
, an
import
statement can be used to import the static members of a class
or interface. This is called
static import
. When using static import, it is possible to refer to
static members directly by their names, without having to qualify them with the name of
their class. This simplifies and shortens the syntax required to use a static member.
To understand the usefulness of static import, let's begin with an example that
does not
use it. The following program computes the solutions to a quadratic equation, which has
this form:
The program uses two static methods from Java's built-in math class
Math
, which is part
of
java.lang
. The first is
Math.pow( )
, which returns a value raised to a specified power.
The second is
Math.sqrt( )
, which returns the square root of its argument.