Sub topic 4
Parsing and Converting with Wrapper Methods
This chapter assumes you know Java primitive types, classes, objects, ==, equals, and basic generic collections such as List<Integer> and Map<String, Integer>. The focus is choosing the correct wrapper method when data must cross a boundary, such as a text file, command-line argument, or user interface.
Parsing text into numbers
Parsing means reading text and creating a numeric value from it. Wrapper classes provide static methods for this job. A static method belongs to the class, so you call it with the class name, such as Integer.parseInt.
The parse methods return primitive values:
| Text | Method | Result type |
|---|---|---|
| `"42"` | `Integer.parseInt("42")` | `int` |
| `"42"` | `Long.parseLong("42")` | `long` |
| `"3.14"` | `Double.parseDouble("3.14")` | `double` |
| `"true"` | `Boolean.parseBoolean("true")` | `boolean` |
public class ParseExample {
public static void main(String[] args) {
String countText = "42";
String priceText = "3.50";
int count = Integer.parseInt(countText);
double price = Double.parseDouble(priceText);
double total = count * price;
System.out.println("Total: " + total);
}
}Integer.parseInt accepts an optional leading sign, so "-12" is valid. It rejects text that is not a valid integer. It also rejects values outside the int range. Invalid input causes NumberFormatException, an unchecked exception that indicates the text cannot be converted.
public class SafeParsing {
public static void main(String[] args) {
String input = "not-a-number";
try {
int value = Integer.parseInt(input);
System.out.println(value);
} catch (NumberFormatException exception) {
System.out.println("Please enter a whole number.");
}
}
}Parsing another number base
The overloaded parseInt method accepts a radix, which is the base used to interpret the digits. Base 10 is decimal. Base 16 is hexadecimal.
public class RadixExample {
public static void main(String[] args) {
int decimal = Integer.parseInt("101", 10); // 101
int binary = Integer.parseInt("101", 2); // 5
int hex = Integer.parseInt("FF", 16); // 255
System.out.println(decimal);
System.out.println(binary);
System.out.println(hex);
}
}The radix does not remove prefixes automatically. For example, "0xFF" is not valid input for parseInt("0xFF", 16). Remove the prefix first or parse the string in a form the method accepts.
`parse` versus `valueOf`
The parse methods return primitives. The valueOf methods return wrapper objects. This distinction matters when a method or collection requires a reference type.
public class ParseAndValueOf {
public static void main(String[] args) {
int primitive = Integer.parseInt("42");
Integer wrapper = Integer.valueOf("42");
System.out.println(primitive);
System.out.println(wrapper);
}
}Java can automatically box the primitive result when needed:
Integer alsoWrapper = Integer.parseInt("42");However, using valueOf states your intention clearly when you need an Integer. The valueOf methods can also reuse suitable cached wrapper objects.
Converting numbers to text
Every wrapper class provides toString methods. The static form converts a primitive or wrapper value to text.
public class NumberToText {
public static void main(String[] args) {
int quantity = 7;
Integer boxed = 12;
String first = Integer.toString(quantity);
String second = boxed.toString();
System.out.println(first + " items");
System.out.println(second);
}
}Concatenation also converts values to text:
String message = "Quantity: " + quantity;Use Integer.toString(value) when you want the conversion to be explicit. For formatting several values, String.format or formatted string methods may be easier to read.
Useful comparison methods
Wrapper classes provide type-specific utilities. Integer.compare(left, right) returns a negative number, zero, or a positive number. It is useful when writing comparisons without subtracting values, because subtraction can overflow.
public class CompareExample {
public static void main(String[] args) {
int result = Integer.compare(10, 20);
if (result < 0) {
System.out.println("10 is smaller");
}
}
}Integer.MAX_VALUE, Integer.MIN_VALUE, and similar constants document the limits of each primitive type.
Exercise
Which method should you use to obtain an int from the text "255" interpreted as hexadecimal, and what value does it produce?
Show answer
Use Integer.parseInt("255", 16). It produces the primitive value 597.