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?
Have a close look at the return types:
Long.parseLong(String)
returns a primitive long
, so there will be re-boxing in this case: Long a = Long.parseLong(str);
.new Long(String)
will create a new Long
object in every case. So, don't do this, but go for 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);
}
}