EN
Java - convert String to long
4
points
In Java, we can convert String to long in couple of different ways.
Short solutions:
// solution 1
long num1 = Long.parseLong("123"); // 123
// solution 2
Long num2 = Long.valueOf("123"); // 123
1. Using Long.parseLong()
public class Example1 {
public static void main(String[] args) {
String str = "123";
long num = Long.parseLong(str);
System.out.println(num); // 123
}
}
Output:
123
2. Using Long.valueOf()
public class Example2 {
public static void main(String[] args) {
String str = "123";
Long num = Long.valueOf(str);
System.out.println(num); // 123
}
}
Output:
123
3. String to long with sign + or -
public class Example3 {
public static void main(String[] args) {
// Long.parseLong() - returns long
System.out.println(Long.parseLong("123")); // 123
System.out.println(Long.parseLong("+123")); // 123
System.out.println(Long.parseLong("-123")); // -123
// Long.valueOf() - returns Long
System.out.println(Long.valueOf("123")); // 123
System.out.println(Long.valueOf("+123")); // 123
System.out.println(Long.valueOf("-123")); // -123
}
}
Output:
123
123
-123
123
123
-123
4. Example of java.lang.NumberFormatException
public class Example4 {
public static void main(String[] args) {
String str = "123a";
long num = Long.parseLong(str);
System.out.println(num);
}
}
Output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "123a"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Long.parseLong(Long.java:589)
at java.lang.Long.parseLong(Long.java:631)
Both methods:
- Long.parseLong("123")
- Long.valueOf("123")
will throw java.lang.NumberFormatException if we try to parse anything else then:
digits or '+', '-' as first character.