EN
Java - convert String to long
4 points
In Java, we can convert String to long in couple of different ways.
Short solutions:
xxxxxxxxxx
1
// solution 1
2
long num1 = Long.parseLong("123"); // 123
3
4
// solution 2
5
Long num2 = Long.valueOf("123"); // 123
xxxxxxxxxx
1
public class Example1 {
2
3
public static void main(String[] args) {
4
String str = "123";
5
long num = Long.parseLong(str);
6
System.out.println(num); // 123
7
}
8
}
Output:
xxxxxxxxxx
1
123
xxxxxxxxxx
1
public class Example2 {
2
3
public static void main(String[] args) {
4
String str = "123";
5
Long num = Long.valueOf(str);
6
System.out.println(num); // 123
7
}
8
}
Output:
xxxxxxxxxx
1
123
xxxxxxxxxx
1
public class Example3 {
2
3
public static void main(String[] args) {
4
5
// Long.parseLong() - returns long
6
System.out.println(Long.parseLong("123")); // 123
7
System.out.println(Long.parseLong("+123")); // 123
8
System.out.println(Long.parseLong("-123")); // -123
9
10
// Long.valueOf() - returns Long
11
System.out.println(Long.valueOf("123")); // 123
12
System.out.println(Long.valueOf("+123")); // 123
13
System.out.println(Long.valueOf("-123")); // -123
14
}
15
}
Output:
xxxxxxxxxx
1
123
2
123
3
-123
4
123
5
123
6
-123
xxxxxxxxxx
1
public class Example4 {
2
3
public static void main(String[] args) {
4
String str = "123a";
5
long num = Long.parseLong(str);
6
System.out.println(num);
7
}
8
}
Output:
xxxxxxxxxx
1
Exception in thread "main" java.lang.NumberFormatException: For input string: "123a"
2
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
3
at java.lang.Long.parseLong(Long.java:589)
4
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.