How to Convert a Java String to int or long Type |Video upload date:  · Duration: PT8M52S  · Language: EN

Quick guide to parse Java strings to int and long with safe parsing examples NumberFormatException handling and practical tips

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.

Basic parsing methods

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.

Protect parsing when input is hostile

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
}

When you need an object value

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)

Parsing other bases without surprises

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)

Avoid throwing exceptions in hot paths

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
    }
}

Lightweight input validation options

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.

  • Use s.matches("\\d+") for unsigned digits when null safety is handled elsewhere
  • Use Character.isDigit per character when you need more control such as allowing a leading minus sign
  • Then call parseInt or parseLong once the format looks sane

Performance tips and practical advice

  • Prefer parseInt when you need a primitive int and want max speed
  • Use valueOf when you need an Integer object or rely on autoboxing
  • Avoid using exceptions for normal control flow because throwing and catching exceptions is costly
  • Specify a radix for non decimal strings to avoid accidental misparsing

Summary and final sanity check

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.