Learn Java: Java Q&A: How do I convert a String to a long?
Developer's Daily Java Q&A Center
  main | java | perl | unix | dev directory | web log
   
Main
Java
Education
Java Q&A Center


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 s2l {

   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 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.

 

Related links

There is much more content related to Java and the String class on the blog, including these posts:


much more at the blog

Copyright 1998-2009 Alvin Alexander, devdaily.com
All Rights Reserved.