Explain Codes LogoExplain Codes Logo

How to convert String to long in Java?

java
long-parse
number-formatting
error-handling
Nikita BarsukovbyNikita Barsukov·Jan 17, 2025
TLDR

To convert a String to a long, utilize Long.parseLong:

long number = Long.parseLong("12345"); // Now you can use the number like never before!

Ensure to handle a potential NumberFormatException for invalid input:

try { long number = Long.parseLong("text"); // Oops, Text can't be converted to a number } catch (NumberFormatException e) { // Handle invalid conversion here }

Selecting the appropriate conversion method

It's crucial to pick the right method for your specific scenario in order to dodge common pitfalls that could lead to inaccurate data.

Decoding Long.parseLong and Long.valueOf

The Long.parseLong method gives you a primitive long, whereas Long.valueOf gives you a Long object:

long parsedLong = Long.parseLong("123"); // Primitive long is ready! Long longObject = Long.valueOf("123"); // Long object, ready for an object-oriented ride!

Radix – transforming number systems

For strings representing numbers in numeric bases other than 10, specify the radix:

long hexToLong = Long.parseLong("126F", 16); // Welcome to the world of hexadecimal!

Dealing with formatted numerical strings

If your string represents a formatted number, use the DecimalFormat class:

DecimalFormat formatter = new DecimalFormat("#,###"); long longFromFormatted = formatter.parse("1,000").longValue(); // Managed to turn 1,000 without losing a single zero!

When exceptions knock your door

Errors or exceptions are part of any coding expedition. Always arm your code with a good error management strategy.

Try-catch: Your safety net

Implementing a try-catch block will effectively catch NumberFormatExceptions:

try { long number = Long.parseLong("123.456"); // Hey, you sneaky decimal point, you can't hide in the long world! } catch (NumberFormatException e) { // Your custom solution goes here }

Expect the unexpected

A good programmer is a prepared programmer. Implement validation for your strings before initiating conversion:

if (strNumber.matches("-?\\d+")) { // Safe to parse, fire away! long number = Long.parseLong(strNumber); } else { // Better luck next...string }

Unlocking best practices and secret tips

Converting Strings to longs might seem straightforward, but with great responsibility comes great...side effects. Here are ways you can ensure a smooth conversion.

Validate first, convert later

Always validate your inputs before you try converting them. It’s not you, it’s them.

Overflow...more like overkill!

For extremely large numbers, beyond the range of long, consider using BigInteger:

BigInteger hugeNumber = new BigInteger("92233720368547758070"); // When 'long' is too short

Alternative libraries: The more, the merrier

Lookout for libraries that could provide you more functionality like Apache's NumberUtils.

long numberFromUtil = NumberUtils.toLong("12345", 0L); // Let Apache do all the heavy lifting!

Radix: Not just a random number

Specify radix carefully. Stick to the script and don't go improvising in the world of radix!