Java – Convert String to Long
To convert a numeric String to a primitive long in Java, use Long.parseLong(). If you need a Long object instead, use Long.valueOf(). Both methods reject invalid, null, or out-of-range input with NumberFormatException.
The examples below cover decimal conversion, invalid input, null values, safe parsing, whitespace, and numbers written in other radices.
1. Convert string to primitive long using Long.parseLong()
Long.parseLong(str) parses a signed decimal string and returns a primitive long. The entire string must represent a valid long value.
In this example, we shall use Long.parseLong() method and pass a string that can be parsed to a valid long value.
Java Program
/**
* Java Program - Convert String to Long
*/
public class StringToLong {
public static void main(String[] args) {
//a string
String str = "18965426354";
//convert string to long
long n = Long.parseLong(str);
System.out.print(n);
}
}
Run the above program and the String is converted to Long.
18965426354
When Long.parseLong() throws NumberFormatException
Long.parseLong() throws NumberFormatException when the string cannot be parsed as a signed decimal long.
Common cases include:
- The string contains characters that are not valid decimal digits, apart from an optional leading
+or-. Examples include"5.354","12L", and"1,000". - The string is empty or
null. - The represented number is outside the
longrange, from-9223372036854775808through9223372036854775807. - The string contains leading or trailing whitespace. If whitespace is expected, remove it before parsing.
In the following example program, we shall take a string which does not contain a valid long value.
Java Program
/**
* Java Program - Convert String to Long
*/
public class StringToLong {
public static void main(String[] args) {
//a string
String str = "5.354"; //"as 9w0", "1as52"
//convert string to long
long n = Long.parseLong(str);
System.out.print(n);
}
}
Run the above program and parseLong() throws NumberFormatException.
Exception in thread "main" java.lang.NumberFormatException: For input string: "5.354"
at java.base/java.lang.NumberFormatException.forInputString(Unknown Source)
at java.base/java.lang.Long.parseLong(Unknown Source)
at java.base/java.lang.Long.parseLong(Unknown Source)
at StringToLong.main(StringToLong.java:12)
Parsing a null String with Long.parseLong()
If null is passed to Long.parseLong(String), Java throws NumberFormatException. A separate NullPointerException catch is not required for this method.
Java Program
/**
* Java Program - Convert String to Long
*/
public class StringToLong {
public static void main(String[] args) {
//a string
String str = null;
//convert string to long
long n = Long.parseLong(str);
System.out.print(n);
}
}
Run the above program and parseLong() throws NumberFormatException. The exact exception message can differ between Java versions.
Exception in thread "main" java.lang.NumberFormatException: null
at java.base/java.lang.Long.parseLong(Unknown Source)
at java.base/java.lang.Long.parseLong(Unknown Source)
at StringToLong.main(StringToLong.java:12)
Handle invalid String-to-long input with try-catch
If the string comes from user input, a file, JSON, or another external source, handle NumberFormatException so invalid input does not terminate the program unexpectedly. See Java Try Catch for the general exception-handling pattern.
/**
* Java Program - Convert String to Long
*/
public class StringToLong {
public static void main(String[] args) {
//a string
String str = "85612536";
long n = 0;
try {
//convert string to long
n = Long.parseLong(str);
} catch (NumberFormatException e) {
System.out.println("Check the string. Not a valid long value.");
} catch (NullPointerException e) {
System.out.println("Check the string. String is null.");
}
System.out.print(n);
}
}
The existing example above also catches NullPointerException, but Long.parseLong(String) reports null input as NumberFormatException. For new code, one NumberFormatException catch is sufficient for null, malformed, empty, and out-of-range strings.
Convert String to long without exposing a parsing exception
Java’s Long class does not provide a tryParseLong() method. If callers should not have to handle an exception, wrap the conversion in a helper method and return an empty result when parsing fails.
import java.util.OptionalLong;
public class StringToLongSafe {
static OptionalLong parseLongSafely(String text) {
try {
return OptionalLong.of(Long.parseLong(text));
} catch (NumberFormatException e) {
return OptionalLong.empty();
}
}
public static void main(String[] args) {
System.out.println(parseLongSafely("123456").orElse(-1));
System.out.println(parseLongSafely("12.5").orElse(-1));
System.out.println(parseLongSafely(null).orElse(-1));
}
}
123456
-1
-1
A preliminary regular-expression check can reject obvious non-numeric text, but it cannot by itself guarantee that a value is inside the long range. Parsing still needs range validation.
2. Convert String to Long object using Long.valueOf()
Long.valueOf(String) parses the string and returns a Long wrapper object. Use it when an API or collection requires Long rather than primitive long.
In the following example, we shall use the method valueOf() to get long value from string.
Java Program
/**
* Java Program - Convert String to Long
*/
public class StringToLong {
public static void main(String[] args) {
//a string
String str = "-632916325";
long n = 0;
//convert string to long
try {
n = Long.valueOf(str);
} catch (NumberFormatException e) {
System.out.println("Check the string. Not a valid long value.");
} catch (NullPointerException e) {
System.out.println("Check the string. String is null.");
}
System.out.print(n);
}
}
In this code, Long.valueOf(str) returns a Long object, which Java automatically unboxes when assigning it to primitive long n. Like parseLong(), valueOf(String) throws NumberFormatException for invalid, null, or out-of-range input.
Long.parseLong() vs Long.valueOf() for String conversion
| Method | Return type | Use when |
|---|---|---|
Long.parseLong(str) | long | You need a primitive numeric value. |
Long.valueOf(str) | Long | You need the wrapper object, such as for List<Long> or a nullable object reference. |
For ordinary numeric calculations, Long.parseLong() is usually the direct choice because it already returns primitive long.
3. Long(String) constructor is deprecated
Note: The Long(String) constructor has been deprecated since Java 9. For new code, use Long.parseLong(String) for a primitive long or Long.valueOf(String) for a Long object.
The following older approach constructs a Long object directly from a string. It may still appear in legacy code.
Java Program
/**
* Java Program - Convert String to Long
*/
public class StringToLong {
public static void main(String[] args) {
try {
Long f = new Long("9223372036854775807");
System.out.print(f);
} catch (NumberFormatException e) {
System.out.println("Check the string. Not a valid long value.");
} catch (NullPointerException e) {
System.out.println("Check the string. String is null.");
}
}
}
Convert hexadecimal or binary String to long with a radix
The two-argument form Long.parseLong(String, int) parses digits using the specified radix. This is useful for binary, octal, hexadecimal, and other bases supported by Java.
public class StringToLongRadix {
public static void main(String[] args) {
long hexValue = Long.parseLong("7fffffff", 16);
long binaryValue = Long.parseLong("101010", 2);
System.out.println(hexValue);
System.out.println(binaryValue);
}
}
2147483647
42
When a radix is supplied, the string should contain the digits for that radix. For example, Long.parseLong("FF", 16) works, while the 0x prefix is not part of the accepted digit sequence for parseLong(String, int). If you specifically need Java-style decimal, hexadecimal, or octal prefixes such as 0x, see Long.decode().
Trim whitespace before converting a String to long
Long.parseLong() does not ignore surrounding whitespace. If input may contain spaces, normalize it first. Check for null before calling strip(), because strip() itself cannot be called on a null reference.
public class StringToLongWhitespace {
public static void main(String[] args) {
String str = " 9876543210 ";
long value = Long.parseLong(str.strip());
System.out.println(value);
}
}
9876543210
Convert StringBuilder text to long in Java
Long.parseLong() accepts a String, so convert a StringBuilder to text first with toString().
StringBuilder builder = new StringBuilder("456789");
long value = Long.parseLong(builder.toString());
System.out.println(value);
456789
Accepted and rejected String formats for Java long parsing
"123","+123", and"-123"are valid decimal strings."12.0"is not valid forLong.parseLong()because a decimal point is not a decimal integer digit."1_000"is not accepted at runtime even though underscores can appear in numeric literals in Java source code."1000L"is not accepted; the source-code suffixLis not part of the string representation parsed byLong.parseLong()."9,000"is not accepted because grouping separators are not valid digits for this method.- Values smaller than
Long.MIN_VALUEor larger thanLong.MAX_VALUEthrowNumberFormatException.
The Java API reference for java.lang.Long documents the accepted formats, radix overloads, return types, and exceptions for these methods.
Choosing the right Java String-to-long conversion
Use Long.parseLong() when you need primitive long, and Long.valueOf() when you need a Long object. Validate or catch NumberFormatException when input can be malformed, null, empty, or outside the long range. Avoid the deprecated Long(String) constructor in new code.
In this Java Tutorial, we learned how to convert a String to a long value in Java using Long.parseLong() and Long.valueOf(), and how to handle common parsing errors.
TutorialKart.com