Java Reference
In-Depth Information
How It Works
The solution illustrates some conversion patterns that work for all the primitive types.
First, there is the conversion of a floating-point number from its human-readable rep-
resentation into the IEEE 754 format used by the Java language for floating-point arith-
metic:
pi = Double.parseDouble("3.14");
Notice the pattern. You can replace
Double
with
Float
, or by
Long
, or by
whatever other type is your target data type. Each primitive type has a corresponding
wrapper class by the same name but with the initial letter uppercase. The primitive type
here is
double
, and the corresponding wrapper is
Double
. The wrapper classes im-
plement helper methods such as
Double.parseDouble()
,
Long.parseLong()
,
Boolean.parseBoolean()
, and so forth. These parse
methods convert human-readable representations into values of the respective types.
Going the other way, it is often easiest to invoke
String.valueOf()
. The
String
class implements this method, and it is overloaded for each of the primitive
data types. Alternatively, the wrapper classes also implement
toString()
methods
that you can invoke to convert values of the underlying type into their human-readable
forms. It's your own preference as to which approach to take.
Conversions targeting the numeric types require some exception handling to be
practical. You generally need to gracefully accommodate a case in which a character-
string value is expected to be a valid numeric representation, but it's not.
Chapter 9
covers exception-handling in detail, and the upcoming Recipe 1-7 provides a simple
example to get you started.
Caution
Literals for the
Boolean
type are
"true"
and
"false"
. They are case-
sensitive. Any value other than these two is silently interpreted as false when converting
from a
String
using the
Boolean parseBoolean()
conversion method.
1-6. Passing Arguments via Command-
Line Execution