Page 196 - Introduction to Programming with Java: A Problem Solving Approach
P. 196

                162 Chapter 5 Using Pre-Built Methods
string to an int, use int’s wrapper class, Integer, to call parseInt. In other words, call Integer. parseInt(<string>) and the string’s corresponding int is returned. Likewise, to convert from a string to a double, use double’s wrapper class, Double, to call parseDouble. In other words, call Double. parseDouble(<string>) and the string’s corresponding double is returned. Later in this section, we’ll show a non-trivial example that uses the wrapper class conversion methods. But first we’ll show some trivial examples to get you used to the method-call syntax. Here we use parseInt and parseDouble to con- vert from strings to primitives:
String yearStr = "2002";
String scoreStr = "78.5";
int year = Integer.parseInt(yearStr);
double score = Double.parseDouble(scoreStr);
To remember the syntax for the string-to-number method calls, think of <type>.parse<type> for Integer.parseInt, Long.parseLong, and so on.
To convert from an int to a string, use int’s wrapper class, Integer, to call toString. In other words, call Integer.toString(<int-value>) and the int value’s corresponding string is returned. Like- wise, to convert from a double to a string, use double’s wrapper class, Double, to call toString. In other words, call Double.toString(<double-value>) and the double value’s corresponding string is returned. Note this example:
int year = 2002;
float score = 78.5;
String yearStr = Integer.toString(year);
String scoreStr = Float.toString(score);
About half of the numerical wrapper-class methods are class methods. We’re focusing on those methods. Since they’re class methods, you call them by prefacing the method call with the wrapper class’s name, just as we have done.
Named Constants
The wrapper classes contain more than just methods; they also contain named constants. All the number wrappers provide named constants for minimum and maximum values. The floating-point wrappers also provide named constants for plus and minus infinity and “Not a Number,” which is the indeterminate value you get if you try to divide zero by zero. Here’s how you access the most important named constants defined in the Integer and Double wrapper classes:
Integer.MAX_VALUE
Integer.MIN_VALUE
Double.MAX_VALUE
Double.MIN_VALUE
Double.POSITIVE_INFINITY
Double.NEGATIVE_INFINITY
Double.NaN
NaN stands for “not a number.”
Apago PDF Enhancer
   There are comparable named constants for the Long and Float wrappers.










































































   194   195   196   197   198