Humus Humus - 2 months ago 13
Java Question

Correct way of converting String to Long in Java

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 a extra step of autoboxing in the first method?

Answer

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