The correct way to convert String to Long in Java

What is the most preferred way to convert String to Long (Object) in Java.

 Long a = new Long(str); 

OR

 Long a = Long.parseLong(str); 

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

+7
java autoboxing
source share
5 answers

Take a close look at return types:

  • Long.parseLong(String) returns a primitive long , so in this case there will be re-boxing: Long a = Long.parseLong(str); .
  • new Long(String) will create a new long object in each case. So do not do this, but go for 3)
  • Long.valueOf(String) returns a long object and returns cached instances for specific values ​​- so if you need long , this is the preferred option.

Checking the source of java.lang.Long , 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); } } 
+12
source share

The best approach is Long.valueOf(str) , because it relies on Long.valueOf(long) , which uses the internal cache, making it more efficient, since it will reuse cached Long instances if necessary, going from -128 to 127 are included.

Returns a Long instance representing the specified long value. If a new long instance is not required, this method should usually be used instead of the Long(long) constructor, since this method is likely to significantly improve the caching space and time of frequently requested values. Note that unlike the corresponding method in the Integer class, this method is not required to cache values ​​in a certain range.

Generally speaking, it’s good practice to use the static factory valueOf(str) of a wrapper class such as Integer , Boolean , Long , ... since most of them reuse instances whenever possible, making them potentially more memory efficient, than the corresponding parse methods or constructors.


Excerpt from Effective Java Item 1 , written by Joshua Bloch :

You can often avoid creating unnecessary objects using a static factory (step 1) instead of constructors on immutable classes that both provide. For example, the static factory method Boolean.valueOf(String) almost always preferable to the Boolean(String) constructor. The constructor creates a new object each time it is called, while a static factory method is never required for this, and usually in practice.

+8
source share

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)) // internally calls to Long.valueOf when you pass string public static Long valueOf(String s) throws NumberFormatException { return Long.valueOf(parseLong(s, 10)); } 
  • 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) { // will cache , range is clearly seen return LongCache.cache[(int)l + offset]; } return new Long(l); } 

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.
+2
source share

From the source code:

 public Long(String s) throws NumberFormatException { this.value = parseLong(s, 10); } 

If you do not believe: enter image description here

+1
source share

From Javadoc:

Creates a newly selected long object, which is the long value specified by the String parameter. The string is converted to a long value exactly as the parseLong method is used for radix 10.

0
source share

All Articles