By Alvin Alexander. Last updated: November 13, 2019
Question: How do I convert a String to a long with Java?
Answer: The Java Long class includes a method named parseLong that serves just this purpose. An example of a simple program that performs this conversion is shown below:
public class StringToLong {
public static void main (String[] args) {
// String s = "fred"; // do this if you want an exception
String s = "100";
try {
long l = Long.parseLong(s.trim()); //<-- String to long here
System.out.println("long l = " + l);
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
}
Other Java “String to long” conversion notes
- Note that I call
trim()on the string I’m converting. If you don’t calltrimand you get a string with blank spaces in it, you’ll get aNumberFormatException. Long.toString(long l)is used to convert in the other direction, fromlongto String.- If you're interested in converting a
Stringto aLongobject, use thevalueOf()method of theLongclass instead of theparseLong()method. - As shown, conversion code like this can throw a NumberFormatException, which you should catch and handle.

