How to convert String to long in Java

  • 23 November 2020
  • ADM

 

How to convert String to long in Java - images/logos/java.jpg

 

To convert a String to long in Java you have two simple options using the static methods from Long class:

  • Long.parseLong(String s): returns a primitive long value;
  • Long.valueOf(String s): returns an Long object.

Ignoring any of the exceptions that can be thrown, all you need to do to convert a String to long is, use on of this lines of code:

long val1 = Long.parseLong(value);
long val2 = Long.valueOf(value);

or

Long obj = Long.valueOf(value);

Note: even if the valueOf method is returning an Long object you can use the primitive long because the boxing and unboxing will be done automatically.

Example

package com.admfactory;

public class LongConverter {

    public static void main(String[] args) {
	String value = "100001";
	/** Use the value to see the exceptions */
//	String value = "number";

	try {
	    long val1 = Long.parseLong(value);
	    System.out.println("val1: " + val1);
	} catch (NumberFormatException e) {
	    e.printStackTrace();
	}

	try {
	    long val2 = Long.valueOf(value);
	    System.out.println("val2: " + val2);
	} catch (NumberFormatException e) {
	    e.printStackTrace();
	}

	try {
	    Long obj = Long.valueOf(value);
	    System.out.println("obj:  " + obj);
	} catch (NumberFormatException e) {
	    e.printStackTrace();
	}
    }
}

Output

If the value string is a valid long like "1", "2", and so on, it will be converted to a Java primitive long with no problem. The output for this will be:

val1: 100
val2: 100
obj:  100

otherwise, if it fails for any reason, the conversion can throw a NumberFormatException, so to capture and deal with the possible error the code need to be used in try/catch block as shown in the example. The output for this case will be:

java.lang.NumberFormatException: For input string: "number"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Long.parseLong(Long.java:441)
	at java.lang.Long.parseLong(Long.java:483)
	at com.admfactory.xml.LongConverter.main(LongConverter.java:10)

 

References