Java Basic Examples

Java convert String to long example

This example shows how to convert String to long in Java. This example also shows how to convert String to long primitive using Long wrapper class.

How to convert String to long in Java?

To convert String to long, use parseLong method of Java Long wrapper class.

This method returns long primitive value by parsing the input String value.


Important Note:

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

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


Here are some of the example String values and their possible long output.

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

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