Tuesday, January 1, 2008

convert a String to a long with Java?

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.



}

No comments :