Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way of converting String to Long in Java [duplicate]

What is the most preferred way of converting a String to Long (the Object) in Java.

Long a = new Long(str);

OR

Long a = Long.parseLong(str);

Is there a correct way here because both seem to have the same level of readability and is it acceptable to add an extra step of autoboxing in the first method?

like image 282
Humus Avatar asked Sep 29 '16 14:09

Humus


2 Answers

Have a close look at the return types:

  1. Long.parseLong(String) returns a primitive long, so there will be re-boxing in this case: Long a = Long.parseLong(str);.
  2. new Long(String) will create a new Long object in every case. So, don't do this, but go for 3)
  3. Long.valueOf(String) returns a Long object, and will return cached instances for certain values -- so if you require a Long this is the preferred variant.

Inspecting the java.lang.Long source, the cache contains the following values (Sun JDK 1.8):

private static class LongCache {
    private LongCache(){}

    static final Long cache[] = new Long[-(-128) + 127 + 1];

    static {
        for(int i = 0; i < cache.length; i++)
            cache[i] = new Long(i - 128);
    }
}
like image 95
qqilihq Avatar answered Sep 22 '22 17:09

qqilihq


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.

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.

like image 22
Nicolas Filotto Avatar answered Sep 23 '22 17:09

Nicolas Filotto