So you have a Java String and you want an int or a long. Welcome to the thrilling world of parsing where bad input will ruin your day. This quick guide gives parsing tips to convert a Java String to primitive types in Java while avoiding NumberFormatException and the usual debugging curse words.
The simplest case is a well behaved decimal string. Integer.parseInt does exactly what it says. If the string is not a valid int Java throws NumberFormatException which is the language's way of saying do not feed it garbage.
int n = Integer.parseInt("123");
Keep this in mind. If the input contains non digits or the numeric value is outside the int range you will hit NumberFormatException. Which is fair. You fed it bad data.
When your numbers get bolder use Long.parseLong. It behaves like Integer.parseInt but for long primitive types so it covers bigger values.
long l = Long.parseLong("1234567890123");
Pick the primitive types based on expected magnitude. If you accidentally choose int and then receive a phone number or timestamp you did not intend to parse you will learn about integer overflow the hard way.
Try catch is not exciting but it is effective. Wrap parsing calls that rely on user input or external data in a targeted catch block.
try {
int n = Integer.parseInt(s);
// use n
} catch (NumberFormatException e) {
// handle bad input, show user friendly message or fallback
}
Use specific catch blocks so you do not accidentally mask other bugs. Logging the offending string is helpful unless you are trying to preserve privacy or hide evidence.
If you need an object rather than a primitive for collections or APIs then use valueOf. It returns the wrapper type and can benefit from caching for small values.
Integer boxed = Integer.valueOf("123");
Long boxedLong = Long.valueOf("1234567890123");
valueOf will still throw NumberFormatException for invalid input. It is not magic, it only wraps the same parsing logic in an object.
If you are tired of repeating try catch everywhere write a small helper. Return null or Optional to indicate invalid input depending on your style and null tolerance.
static Integer tryParseInt(String s) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
return null; // or use Optional
}
}
static java.util.Optional tryParseIntOptional(String s) {
try {
return java.util.Optional.of(Integer.parseInt(s));
} catch (NumberFormatException e) {
return java.util.Optional.empty();
}
}
Use Optional when you want callers to handle absence explicitly. Use null when you are writing quick scripts and have a death wish.
To convert a Java String to int or long primitive types use Integer.parseInt and Long.parseLong when you trust the input. Catch NumberFormatException for untrusted data. Use valueOf when you need wrapper types. Consider a tryParse helper to make parsing code readable and reduce repeated try catch blocks.
Follow these parsing tips and your runtime surprises will drop, which means fewer frantic searches through stack traces at 2 a m. You are welcome.
I know how you can get Azure Certified, Google Cloud Certified and AWS Certified. It's a cool certification exam simulator site called certificationexams.pro. Check it out, and tell them Cameron sent ya!
This is a dedicated watch page for a single video.