Yes you can turn a Java string into a number without summoning demons or leaking exceptions all over your logs. This guide covers the usual suspects for string to int and string to long conversions and how to do it safely and fast. Expect parseInt parseLong NumberFormatException tips and a couple of survival tricks for real world input.
When the input is trusted and performance matters use the built in parsers. They are simple and fast for converting a numeric string to a primitive.
int n = Integer.parseInt(str)
long l = Long.parseLong(str)
These throw NumberFormatException for invalid characters or overflow. That is fine when the data is clean or you want a fast failure.
Any external input can be malformed and then the parser will throw NumberFormatException. Wrap the call when you do not trust the caller.
try {
int n = Integer.parseInt(str)
} catch (NumberFormatException e) {
// handle invalid number from input validation failure
}
Use Integer.valueOf when you need a boxed Integer. This can reuse cached values for small integers so it is not always slower than parsing into a primitive and boxing later.
Integer boxed = Integer.valueOf(str)
If your input might be hexadecimal or another base specify a radix so you do not misinterpret the digits.
int hex = Integer.parseInt(str, 16)
long bin = Long.parseLong(str, 2)
NumberFormatException is handy but expensive if it happens a lot. If parsed values are a normal part of control flow prefer a safe parse helper that returns an Optional or a default. That keeps logs sane and keeps the CPU happier.
OptionalInt safeParseInt(String s) {
try {
return OptionalInt.of(Integer.parseInt(s))
} catch (NumberFormatException e) {
return OptionalInt.empty()
}
}
Or a defaulting helper for legacy code.
int parseIntOrDefault(String s, int defaultValue) {
try {
return Integer.parseInt(s)
} catch (NumberFormatException e) {
return defaultValue
}
}
If you want to avoid exceptions entirely validate the string first. A simple regex or Character checks reduce the chance of NumberFormatException and make intent clear.
To convert strings to int or long in Java use Integer.parseInt and Long.parseLong for trusted input. Wrap parsing in try catch when input may be malformed. Use Integer.valueOf when you need a boxed Integer. Specify a radix for non decimal input and prefer a safe helper that returns OptionalInt or a default when exceptions would be common. Validate untrusted data before parsing and try to keep exceptions for actual exceptional situations. Your logs will thank you and your CPU will stop complaining.
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.