How to convert String to long in Java?

JavaString

Java Problem Overview


I got a simple question in Java: How can I convert a String that was obtained by Long.toString() to long?

Java Solutions


Solution 1 - Java

Use Long.parseLong()

 Long.parseLong("0", 10)        // returns 0L
 Long.parseLong("473", 10)      // returns 473L
 Long.parseLong("-0", 10)       // returns 0L
 Long.parseLong("-FF", 16)      // returns -255L
 Long.parseLong("1100110", 2)   // returns 102L
 Long.parseLong("99", 8)        // throws a NumberFormatException
 Long.parseLong("Hazelnut", 10) // throws a NumberFormatException
 Long.parseLong("Hazelnut", 36) // returns 1356099454469L
 Long.parseLong("999")          // returns 999L

Solution 2 - Java

To convert a String to a Long (object), use Long.valueOf(String s).longValue();

See link

Solution 3 - Java

public class StringToLong {

   public static void main (String[] args) {

      // String s = "fred";    // do this if you want an exception

      String s = "100";

      try {
         long l = Long.parseLong(s);
         System.out.println("long l = " + l);
      } catch (NumberFormatException nfe) {
         System.out.println("NumberFormatException: " + nfe.getMessage());
      }

   }
}

Solution 4 - Java

Long.valueOf(String s) - obviously due care must be taken to protect against non-numbers if that is possible in your code.

Solution 5 - Java

There are a few ways to convert String to long:

long l = Long.parseLong("200"); 
String numberAsString = "1234";
long number = Long.valueOf(numberAsString).longValue();
String numberAsString = "1234";
Long longObject = new Long(numberAsString);
long number = longObject.longValue();

We can shorten to:

String numberAsString = "1234";
long number = new Long(numberAsString).longValue();

Or just

long number = new Long("1234").longValue();
  1. Using Decimal format:
String numberAsString = "1234";
DecimalFormat decimalFormat = new DecimalFormat("#");
try {
    long number = decimalFormat.parse(numberAsString).longValue();
    System.out.println("The number is: " + number);
} catch (ParseException e) {
    System.out.println(numberAsString + " is not a valid number.");
}

Solution 6 - Java

The best approach is Long.valueOf(str) as it relies on Long.valueOf(long) which uses an internal cache making it more efficient since it will reuse if needed the cached instances of Long going from -128 to 127 included.

> Returns a Long instance representing the specified long value. If a > new Long instance is not required, this method should generally be > used in preference to the constructor Long(long), as this method is > likely to yield significantly better space and time performance by > caching frequently requested values. Note that unlike the > corresponding method in the Integer class, this method is not required > to cache values within a particular range.

Thanks to auto-unboxing allowing to convert a wrapper class's instance into its corresponding primitive type, the code would then be:

long val = Long.valueOf(str);

Please note that the previous code can still throw a NumberFormatException if the provided String doesn't match with a signed long.

Generally speaking, it is a good practice to use the static factory method valueOf(str) of a wrapper class like Integer, Boolean, Long, ... since most of them reuse instances whenever it is possible making them potentially more efficient in term of memory footprint than the corresponding parse methods or constructors.


Excerpt from Effective Java Item 1 written by Joshua Bloch:

> You can often avoid creating unnecessary objects by using static > factory methods (Item 1) in preference to constructors on immutable > classes that provide both. For example, the static factory method > Boolean.valueOf(String) is almost always preferable to the > constructor Boolean(String). The constructor creates a new object > each time it’s called, while the static factory method is never > required to do so and won’t in practice.

Solution 7 - Java

It's quite simple, use Long.valueOf(String s);

For example:

String s;
long l;

Scanner sc=new Scanner(System.in);
s=sc.next();
l=Long.valueOf(s);
System.out.print(l);

You're done!!!

Solution 8 - Java

For those who switched to Kotlin just use
string.toLong()
That will call Long.parseLong(string) under the hood

Solution 9 - Java

First of all you need to check if the String to be converted to Long is not null and is really Long to avoid NumberFormatException. To do that the best way is to create a new method like this:

    public static Long convertStringToLong(String str) {
		try {
			return Long.valueOf(str);
		} catch (NumberFormatException e) {
			return null;
		}
	}

Solution 10 - Java

In case you are using the Map with out generic, then you need to convert the value into String and then try to convert to Long. Below is sample code

	Map map = new HashMap();

	map.put("name", "John");
	map.put("time", "9648512236521");
	map.put("age", "25");

	long time = Long.valueOf((String)map.get("time")).longValue() ;
	int age = Integer.valueOf((String)  map.get("aget")).intValue();
	System.out.println(time);
	System.out.println(age);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBelgiView Question on Stackoverflow
Solution 1 - JavaMike ChristensenView Answer on Stackoverflow
Solution 2 - JavacoreyspitzerView Answer on Stackoverflow
Solution 3 - JavaGenjuroView Answer on Stackoverflow
Solution 4 - JavamarkdsieversView Answer on Stackoverflow
Solution 5 - JavaHoque MD ZahidulView Answer on Stackoverflow
Solution 6 - JavaNicolas FilottoView Answer on Stackoverflow
Solution 7 - JavaPrajwal ShindeView Answer on Stackoverflow
Solution 8 - JavaLeonid UstenkoView Answer on Stackoverflow
Solution 9 - JavaMohamed Aymen CharradaView Answer on Stackoverflow
Solution 10 - JavaChetan NellekeriView Answer on Stackoverflow