Skip to content

Java convert String to long example

This example shows how to convert String to long in Java using the parseLong method of the Long wrapper class including NumberFormatException.

How to convert String to long in Java?

To convert a string to a long primitive value, use the parseLong method of the Long wrapper class.

This method returns a long primitive value by parsing the input string value.

Output

Important Note:

All the characters in the string must be a digit, except for the first character of the string which can be a “-” (minus sign) to indicate a negative numeric value.

If any of the characters in the string (except for the first character, if it is a minus sign) is a non-digit character, the NumberFormatException exception is thrown while converting from string to a long value.

Output

Here are some of the example string values and their possible long outputs.

Please note that the “+” (plus sign) is allowed as the first character of the string in newer versions of Java. In older versions, if the string has a plus sign as a first character, the parseLong method throws a NumberFormatException exception.

This example is a part of the Java Basic Examples and Java Type conversion Tutorial.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.