How to convert a String to long in Java

We can convert a String to a primitive long using the Long.parseLong method or to a wrapped Long class using the Long.valueOf. When both methods receive an invalid number as argument, a java.lang.NumberFormatException will be thrown.

Convert a String to long using Long.parseLong

The Long.parseLong method is used to convert a String to primitive long.

String number = "1234";
long convertedNumber = Long.parseLong(number);
System.out.println("Convert String to long: " + convertedNumber);

String negativeNumber = "-1234";
long convertedNegativeNumber = Long.parseLong(negativeNumber);
System.out.println("Convert negative String to long: " + convertedNegativeNumber);

The previous will generate the following output.

Convert String to long: 1234
Convert negative String to long: -1234

Convert a String to Long using Long.valueOf

The Long.valueOf method is used to convert a String to a wrappedLong.

 String number = "1234";
 Long convertedNumber = Long.valueOf(number);
 System.out.println("Convert String to Long: " + convertedNumber);

 String negativeNumber = "-1234";
 Long convertedNegativeNumber = Long.valueOf(negativeNumber);
 System.out.println("Convert negative String to Long: " + convertedNegativeNumber);

The previous will generate the following output.

Convert String to Long: 1234
Convert negative String to Long: -1234

throws java.lang.NumberFormatException

If the String passed in is not a valid Long, an java.lang.NumberFormatException is thrown. In this example "-abc" is not a valid number for type Long.

String invalidNumber = "-abc";
long invalidConvertedNumber = Long.parseLong(invalidNumber);

The java.lang.NumberFormatException thrown.

Exception in thread "main" java.lang.NumberFormatException: For input string: "-abc"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Long.parseLong(Long.java:589)
	at java.lang.Long.parseLong(Long.java:631)
	at com.memorynotfound.ParseLongExample.main(ParseLongExample.java:16)

References

Download

Download it ! – convert-string-to-long-java

You may also like...