Sub topic 4
Parsing and converting with wrapper methods
Earlier chapters showed how the compiler boxes and unboxes values for you. This chapter covers the conversions that the compiler does not do: text to number, number to text, one numeric type to another, and one number base to another. The wrapper classes (Integer, Long, Double, Boolean, Character and the rest) provide these as static and instance methods.
This chapter assumes you know the primitive types, can read basic class and method syntax, and have seen try/catch. It also assumes you know what Integer is and that Integer.valueOf returns an object. Caching and == come in a later chapter.
The conversion map
Almost every conversion falls into one of three families, and each has a predictable method name.
| Direction | Method pattern | Example | Result type |
|---|---|---|---|
| String to primitive | `parseXxx(String)` | `Integer.parseInt("12")` | `int` |
| String to wrapper | `valueOf(String)` | `Integer.valueOf("12")` | `Integer` |
| Primitive to wrapper | `valueOf(primitive)` | `Integer.valueOf(12)` | `Integer` |
| Wrapper to primitive | `xxxValue()` | `boxed.intValue()` | `int` |
| Anything to String | `toString(...)`, `String.valueOf(...)` | `Integer.toString(12)` | `String` |
The rule of thumb is that parseXxx returns a primitive and valueOf returns a wrapper. Pick the one that matches what you need, so you do not box a value only to unbox it again.
Basic conversions
public class ParseBasics {
public static void main(String[] args) {
int a = Integer.parseInt("123"); // String -> int
Integer b = Integer.valueOf("123"); // String -> Integer
String s1 = Integer.toString(a); // int -> String
String s2 = String.valueOf(a); // int -> String (works for any type)
String s3 = "" + a; // concatenation also converts
double d = Double.parseDouble("3.5");
long l = Long.parseLong("9000000000");
boolean flag = Boolean.parseBoolean("TRUE");
System.out.println(a + " " + b + " " + s1 + s2 + s3 + " " + d + " " + l + " " + flag);
}
}String.valueOf accepts any type, including char[], Object and every primitive. For a wrapper that may be null, String.valueOf(obj) returns the text "null", while obj.toString() throws a NullPointerException. Objects.toString(obj, "default") lets you choose the fallback text.
What parseInt accepts and rejects
Integer.parseInt is strict. It throws NumberFormatException, an unchecked exception, when the text is not exactly a valid number. The details surprise people.
public class ParseFailures {
static void tryParse(String text) {
try {
System.out.println("'" + text + "' -> " + Integer.parseInt(text));
} catch (NumberFormatException e) {
System.out.println("'" + text + "' fails: " + e.getMessage());
}
}
public static void main(String[] args) {
tryParse("42"); // ok
tryParse("+42"); // ok: a leading plus sign is allowed
tryParse("-0"); // ok: 0
tryParse(" 42"); // fails: whitespace is not trimmed
tryParse("42.0"); // fails: not an integer literal
tryParse("1_000"); // fails: underscores are only valid in source code
tryParse("2147483648"); // fails: exceeds Integer.MAX_VALUE
tryParse(""); // fails: empty string
tryParse(null); // fails: also NumberFormatException, not NullPointerException
}
}Points to remember:
parseIntdoes not trim whitespace. Calltrim()orstrip()first if the input comes from users or files.- It accepts an optional
+or-sign, then digits. It never accepts a decimal point, an exponent, a thousands separator, or a type suffix such asL. - It does not use the default locale.
"1,234"fails even in locales that group digits with commas. Usejava.text.NumberFormatfor locale-aware parsing. - Overflow is an error, not a wrap-around. Use
Long.parseLongif values may exceed theintrange. - Digits are matched with
Character.digit, so non-ASCII decimal digits, such as Arabic-Indic digits, also parse. Validate input if you need ASCII only.
The floating-point and boolean parsers
Double.parseDouble and Float.parseFloat are more forgiving than the integer parsers.
public class ParseDoubles {
public static void main(String[] args) {
System.out.println(Double.parseDouble(" 1.5 ")); // 1.5: surrounding whitespace is trimmed
System.out.println(Double.parseDouble("1e3")); // 1000.0: exponent notation
System.out.println(Double.parseDouble("1.5f")); // 1.5: f and d suffixes are accepted
System.out.println(Double.parseDouble("NaN")); // NaN
System.out.println(Double.parseDouble("-Infinity")); // -Infinity
System.out.println(Boolean.parseBoolean("true")); // true
System.out.println(Boolean.parseBoolean("TRUE")); // true: case-insensitive
System.out.println(Boolean.parseBoolean("yes")); // false: anything else is false
System.out.println(Boolean.parseBoolean(null)); // false: no exception
try {
Double.parseDouble("1,5"); // comma decimal separator is rejected
} catch (NumberFormatException e) {
System.out.println("1,5 is not a valid double");
}
}
}Boolean.parseBoolean never throws. It returns true only when the text equals "true" ignoring case, so a typo such as "ture" silently becomes false. If invalid input should be an error, check the text yourself before calling it.
Number bases and unsigned values
Each integer wrapper has an overload that takes a radix (the number base, from 2 to 36). The reverse direction produces text in a chosen base.
public class Radix {
public static void main(String[] args) {
System.out.println(Integer.parseInt("ff", 16)); // 255
System.out.println(Integer.parseInt("-101", 2)); // -5
System.out.println(Integer.toString(255, 16)); // ff
System.out.println(Integer.toBinaryString(10)); // 1010
System.out.println(Integer.toHexString(-1)); // ffffffff: two's complement bits
System.out.println(Integer.toOctalString(8)); // 10
System.out.println(Integer.decode("0x1F")); // 31: understands 0x, # and leading 0
System.out.println(Integer.decode("010")); // 8: leading zero means octal
System.out.println(Integer.parseUnsignedInt("4294967295")); // -1: same 32 bits as unsigned max
System.out.println(Integer.toUnsignedString(-1)); // 4294967295
}
}Two details matter here. toHexString, toBinaryString and toOctalString treat the value as unsigned bits, so negative numbers print as a full 32-bit pattern and never get a minus sign. Integer.toString(int, radix) does the opposite and prints a signed value, so Integer.toString(-255, 16) gives -ff. Integer.decode follows Java source-literal prefixes, which is why "010" is 8 and not 10. Plain parseInt("010") returns 10.
Converting between numeric types with xxxValue
Every numeric wrapper extends Number, which declares intValue(), longValue(), doubleValue(), floatValue(), shortValue() and byteValue(). These behave exactly like a primitive cast, which means a narrowing conversion can lose information without any error.
public class NarrowingValues {
public static void main(String[] args) {
Double pos = 3.99;
Double neg = -3.99;
System.out.println(pos.intValue()); // 3: truncates toward zero
System.out.println(neg.intValue()); // -3
System.out.println(Math.round(pos)); // 4: rounds to nearest, returns long
Long big = 4_294_967_297L; // 2^32 + 1
System.out.println(big.intValue()); // 1: high bits are discarded
System.out.println(Integer.valueOf(300).byteValue()); // 44: 300 - 256
System.out.println(Double.valueOf(1e20).intValue()); // 2147483647: saturates at the maximum
try {
Math.toIntExact(big); // throws instead of wrapping
} catch (ArithmeticException e) {
System.out.println("toIntExact: " + e.getMessage());
}
}
}Integer narrowing wraps around, and floating-point to integer conversion truncates and saturates, with NaN becoming 0. When the value must fit, use Math.toIntExact, which throws ArithmeticException on overflow.
Characters and digits
char is a numeric type, so converting between a digit character and its numeric value is a common mistake.
public class CharDigits {
public static void main(String[] args) {
char c = '7';
System.out.println((int) c); // 55: the character code, not the digit
System.out.println(c - '0'); // 7: classic digit arithmetic
System.out.println(Character.digit(c, 10)); // 7: -1 if c is not a digit in that radix
System.out.println(Character.digit('f', 16)); // 15
System.out.println(Character.getNumericValue('a')); // 10: letters have numeric values too
System.out.println(Character.forDigit(11, 16)); // b
System.out.println(Character.isDigit('x')); // false
}
}Prefer Character.digit(c, radix) for validation, since it returns -1 for invalid input. getNumericValue returns 10 to 35 for letters, so it can accept characters you meant to reject.
Parsing safely
Because NumberFormatException is unchecked, nothing forces callers to handle it. A small helper that returns a value or a default keeps parsing code in one place. Wrapping it in OptionalInt makes "no valid number" a normal result.
import java.util.OptionalInt;
public class SafeParse {
static OptionalInt parseIntSafe(String text) {
if (text == null) {
return OptionalInt.empty();
}
try {
return OptionalInt.of(Integer.parseInt(text.trim()));
} catch (NumberFormatException e) {
return OptionalInt.empty();
}
}
public static void main(String[] args) {
String[] inputs = {"17", " 17 ", "seventeen", null, "99999999999"};
for (String input : inputs) {
System.out.println(input + " -> " + parseIntSafe(input).orElse(-1));
}
}
}This prints 17, 17, then -1 for the three invalid inputs. Using a sentinel such as -1 is only safe when it cannot be a real value. When it could be, keep the OptionalInt and let the caller decide.
Other useful static helpers
The wrapper classes also carry small utilities that avoid writing your own versions or boxing by accident.
Integer.compare(a, b)returns a negative number, zero or a positive number. It is the safe way to write comparators, sincea - bcan overflow.Integer.sum,Integer.maxandInteger.minare method references for streams, such asreduce(0, Integer::sum).Integer.MAX_VALUE,Integer.MIN_VALUEandLong.MAX_VALUEexpose the limits, andInteger.BYTESandInteger.SIZEgive the width in bytes and bits.Integer.signum(x)returns -1, 0 or 1.Double.isNaN(x),Double.isInfinite(x)andDouble.isFinite(x)test special values.Double.compareorders them consistently.Integer.hashCode(int)computes the hash of a primitive without creating an object.
Common mistakes
- Parsing user input without trimming, then getting a
NumberFormatExceptionon"42 ". - Calling
Integer.valueOf(text)when a primitive is needed. The result is unboxed immediately, and for values outside the cache it allocates first. - Expecting
Boolean.parseBoolean("yes")or"1"to betrue. - Using
(int) cto turn a digit character into a number and getting 48 to 57. - Narrowing with
intValue()on aLongthat may be large, and getting a wrapped result with no error. - Assuming
Integer.parseInt(null)throwsNullPointerException. It throwsNumberFormatException, so a singlecatchcovers both bad text andnull.
Exercise
What does each expression produce: Integer.parseInt("+7"), Integer.parseInt(" 7"), Boolean.parseBoolean("yes"), and Double.parseDouble("7f")?
Show answer
Integer.parseInt("+7") returns 7, because a leading plus sign is allowed. Integer.parseInt(" 7") throws NumberFormatException, because the leading space is not trimmed. Boolean.parseBoolean("yes") returns false, because only "true" ignoring case yields true. Double.parseDouble("7f") returns 7.0, because floating-point parsing accepts a trailing f or d suffix.
Exercise
Given Long big = 5_000_000_000L;, what does big.intValue() return in relation to the original value, and which standard method would you use to detect the problem instead?
Show answer
big.intValue() silently discards the high 32 bits, so it returns 705032704 instead of 5000000000. Use Math.toIntExact(big), which throws ArithmeticException when the value does not fit in an int.
Exercise
Write a method static int hexToInt(String text) that returns the value of a hexadecimal string such as "ff" or "1A", and returns -1 if the text is not valid hexadecimal. Do not use a regular expression.
Show answer
static int hexToInt(String text) { if (text == null) { return -1; } try { return Integer.parseInt(text.trim(), 16); } catch (NumberFormatException e) { return -1; } } This uses the radix overload of parseInt. It handles null explicitly, trims whitespace, and turns NumberFormatException into the -1 sentinel. Note that parseInt also accepts a leading sign, so "-ff" returns -255.