This example shows how to convert String to long in Java using the parseLong method of the Long wrapper class including NumberFormatException.
How to convert String to long in Java?
To convert a string to a long primitive value, use the parseLong
method of the Long wrapper class.
1 |
public static long parseLong(String strLongNumber) |
This method returns a long primitive value by parsing the input string value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
package com.javacodeexamples.basic; public class StringToLongExample { public static void main(String[] args){ String strNumber = "234234"; /* * use Long.parseLong() method to * convert string to long primitive value */ long l = Long.parseLong(strNumber); System.out.println("String to long: " + l); } } |
Output
1 |
String to long: 234234 |
Important Note:
All the characters in the string must be a digit, except for the first character of the string which can be a “-” (minus sign) to indicate a negative numeric value.
If any of the characters in the string (except for the first character, if it is a minus sign) is a non-digit character, the NumberFormatException exception is thrown while converting from string to a long value.
1 2 |
String strNumber = "234.234"; long l = Long.parseLong(strNumber); |
Output
1 2 3 4 5 |
Exception in thread "main" java.lang.NumberFormatException: For input string: "234.234" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Long.parseLong(Unknown Source) at java.lang.Long.parseLong(Unknown Source) at com.javacodeexamples.basic.StringToLongExample.main(StringToLongExample.java:19) |
Here are some of the example string values and their possible long outputs.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
//4322 System.out.println( Long.parseLong("4322") ); //NumberFormatException System.out.println( Long.parseLong("4221312.321") ); //-4322 System.out.println( Long.parseLong("-4322") ); //NumberFormatException System.out.println( Long.parseLong("8347a") ); //remove leading zeros - 534547 System.out.println( Long.parseLong("00534547") ); //NumberFormatException in older version of Java, 9453 in newer versions System.out.println( Long.parseLong("+9453") ); /* * 'l' or 'L' as a last character is not allowed. * NumberFormatException */ System.out.println( Long.parseLong("345232322L") ); /* * even empty string is not allowed, * NumberFormatException is thrown for input String: "" */ System.out.println( Integer.parseInt("") ); |
Please note that the “+” (plus sign) is allowed as the first character of the string in newer versions of Java. In older versions, if the string has a plus sign as a first character, the parseLong
method throws a NumberFormatException exception.
This example is a part of the Java Basic Examples and Java Type conversion Tutorial.
Please let me know your views in the comments section below.