Home » Java » How to convert String to long in Java?

How to convert String to long in Java?

Posted by: admin November 2, 2017 Leave a comment

Questions:

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

Answers:
 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

Questions:
Answers:

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

See link

Questions:
Answers:
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());
      }

   }
}

Questions:
Answers:

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

Questions:
Answers:

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.

Questions:
Answers:

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