How do I convert a String to a long with Java?

Question: How do I convert a String to a long with Java?

Answer: The 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());
         System.out.println("long l = " + l);
      } catch (NumberFormatException nfe) {
         System.out.println("NumberFormatException: " + nfe.getMessage());


Other Java String to long notes

  • Long.toString(long l) is used to convert in the other direction, from long to String.
  • If you're interested in converting a String to a Long object, use the valueOf() method of the Long class instead of the parseLong() method.
  • As shown, conversion code like this can throw a NumberFormatException, which you should catch and handle.


why do you use trim() here?
I have read explanation for that, but i do not get it.
please explain it to me

Long.parseLong throws an exception on spaces

The trim() method removes any whitespace from around the value you're given. So, if you get a String like " 11 ", it will turn that String into "11" before attempting the conversion.

This is needed because the Long.parseLong() method will throw an exception if you give it a String with spaces in it, like " 11 ".

Post new comment

The content of this field is kept private and will not be shown publicly.