I would suggest using Long.parseLong for every other option, because:
- Every other function ie
Long.valueOf , Long(string) relies on the Long.parseLong method, which works as the main method for every String to Long transformation. - As for caching, this will work if your input is only between -128 to 127 (see the example below), so it's up to the encoder that you want to call
Long.parseLong directly or through Long.valueOf when your object is of type String (obviously use a direct call). official documents and a link to the source code (why not use a byte instead of Long, because the cache will not save any long value, even this range applies to integers).
From official documents
public static Long valueOf(String s) throws NumberFormatException Returns a Long object holding the value of the specified String. The argument is interpreted as representing a signed decimal long, exactly as if the argument were given to the parseLong(java.lang.String) method. The result is a Long object that represents the integer value specified by the string. **In other words, this method returns a Long object equal to the value of:** new Long(Long.parseLong(s))
- About
Long.valueOf returns a direct Wrapper object without creating a new Long object. new Long is a false statement, because according to the internal use of Long.parseLong (which returns a primitive long), the primitive output of Long.parseLong will be converted to a Wrapper object, creating a new object of class Long . so you want to use direct Boxing or you can call Long.valueOf=>Long.parseLong=>new Long
A bit more about caching (if pass long):
The cache is of little use if you want to use == to check for equality (for example, an intern string) with the type of an object. A long cache will only store a static array of objects whose value is between -128 to 127 , including the range, so if your number is outside this range, you cannot use == to check for equality (you do not believe it, try to give an example)
Example:
Long b2=128L; Long b3=128L; Long aa=Long.valueOf("134"); Long ab=Long.valueOf("134"); System.out.println(b2==b3); // no cache for out of range values System.out.println(aa==ab); // no cache for out of range values System.out.println(aa.equals(ab)); // must use equals for equality check System.out.println(b2.equals(b3)); b2=44; // between -128 to 127 it will work b3=44; System.out.println(b2==b3);
Exit:
false false true true true
So try using equals to check for equality.
Why do we need a cache code : because a number between -128 to 127 inclusively must be assigned an identity for JLS performance reasons (5.1.7) , so the cache is not intended to save time and space in this case.
public static Long valueOf(long l) { final int offset = 128; if (l >= -128 && l <= 127) {
Output:
- Use
Long.parseLong . - Must use equals when working with Wrapper classes.
- The cache for the java mechanism only works if you want to use numbers from -128 to 127 with
Wrapper classes.
Pavneet_Singh
source share