474

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

2

11 Answers 11

755

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
1
154

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

See link

4
  • 7
    @Belgi. No, it returns java.lang.Long Oct 7, 2011 at 22:20
  • @Belgi - Long.valueOf returns a Long, not a string.
    – Don Roby
    Oct 7, 2011 at 22:20
  • 5
    @MikeDaniels, Because this is a very indirect way of doing it. See docs.oracle.com/javase/7/docs/api/java/lang/…, it returns a Long object not the primitive long.
    – Pacerier
    Jun 17, 2014 at 21:31
  • 3
    Long.valueOf(String s) gives a Long (object) and Long.valueOf(String s).longValue() gives the long (primitive).
    – Champ
    Aug 29, 2016 at 16:38
32
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());
      }

   }
}
0
15

There are a few ways to convert String to long:

1)

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.");
}
14

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

0
8

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.

1
  • 1
    It's worth noting that auto-unboxing is "desugared" by the compiler into, for the case of long -> Long, Long.valueOf(primitiveLong). So Long number = Long.valueOf("123"), Long number = Long.parseLong("123") and Long number = Long.valueOf(Long.parseString("123") all end up doing pretty much the same thing. What you do want to be careful about is not calling constructors of the boxed primitive classes - that can be wasteful. So don't write Long number = new Long(parseLong("123")) Jun 27, 2017 at 22:20
3

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!!!

1

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

1

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;
        }
    }
1

Convert String to Long Value you need to use

Long.valueOf((AppSessionManager.getContactNo())).longValue();

you can use try-catch for NumberFormatException

 try {
     Long.valueOf((AppSessionManager.getContactNo())).longValue();
  } catch (NumberFormatException nfe) {
     System.out.println("NumberFormatException: " + nfe.getMessage());
  }
-1

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);

Not the answer you're looking for? Browse other questions tagged or ask your own question.