Java encode string to long

Convert String to long in Java

Learn to convert a String to Long type in Java using Long.parseLong(String) , Long.valueOf(String) methods and new Long(String) constructor.

String number = "2018"; //String long value1 = Long.parseLong( number, 10 ); long value2 = Long.valueOf( number ); long value3 = new Long( number ); 

1. Using Long.valueOf(String)

The Long.valueOf() method parses the input string to a signed decimal long type. The characters in the string must all be decimal digits, except that the first character may be a minus (-) sign for negative numbers and a plus(+) sign for positive numbers.

The result long value is exactly the same as the string argument in base 10. In the following example, we convert one positive and one negative number to a long value.

String positiveNumber = "+12001"; long value1 = Long.valueOf(positiveNumber); //12001L String negativeNumber = "-22002"; long value2 = Long.valueOf(negativeNumber); //-22002L

If the string cannot be parsed as a long, it throws NumberFormatException.

Assertions.assertThrows(NumberFormatException.class, () -> < Long.valueOf("alexa"); >);

2. Using Long.parseLong(String)

The rules for Long.parseLong(String) method are similar to Long.valueOf(String) method as well.

  • It parses the String argument as a signed decimal long type value.
  • The characters in the string must all be decimal digits, except that the first character may be a minus (-) sign for negative numbers and a plus(+) sign for positive numbers.
  • The result long value is exactly the same as the string argument in base 10.

Again, we will convert one positive number and one negative number to long value using parseLong() API.

String positiveNumber = "+12001"; long value1 = Long.parseLong(positiveNumber); //12001L String negativeNumber = "-22002"; long value2 = Long.parseLong(negativeNumber); //-22002L

If the input String is in another base then we can pass the base as second input to the method.

String numberInHex = "-FF"; long value = Long.parseLong(numberInHex); //-255L

3. Using new Long(String) Constructor

Another useful way is to utilize Long class constructor to create new long object. This method has been deprecated since Java 9, and recommended to use parseLong() API as discussed above.

long value = new Long("100"); //100L

Using any of the given approaches, if the input String does not have only the decimal characters (except the first character, which can be plus or minus sign), we will get NumberFormatException error in runtime.

String number = "12001xyz"; long value = Long.parseLong(number); //Error Exception in thread "main" java.lang.NumberFormatException: For input string: "12001xyz" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Long.parseLong(Long.java:589) at java.lang.Long.<init>(Long.java:965) at com.howtodoinjava.StringExample.main(StringExample.java:9)

Источник

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

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?

i am little curious, why would somebody want caching for a single object as question also suggest converting a single string object to long

Читайте также:  Php ini file extension

@PavneetSingh Those things might happen in a loop or through a long period, Long instances might get put into collections, millions of instances. In this case (and when most of the values can actually be retrieved from the cache), caching can save a considerable amount of memory.

@qqilihq first cache can’t store million of instance plus it’s range is very very limited and basically it’s for java internal implementation not for enhancing performance ,for more clear information read my answer below (don’t know why someone would down-vote it maybe did it on purpose ) :P:P

5 Answers 5

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

i posted my answer just to guide others and though maybe for other good community member like you,to rectify your mistake instead you are trying to prove the official docs wrong which you can’t

@PavneetSingh Please be specific, about my «mistake» and where I would be trying to prove anything wrong.

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.

I would like to suggest using Long.parseLong over every other option because :

  • Every other function i.e Long.valueOf , Long(string) relies on Long.parseLong method which works as a core method for every String to Long conversion.
  • As about caching, this will work when your input is only between -128 to 127 (see the Example below) so it’s up to the coder that you want to call Long.parseLong directly or through Long.valueOf when your object is of String type.(obviously, use direct call).official docs and the source code link (why don’t use Byte instead of Long then because cache won’t save every long value even this range apply for Integers too)
Читайте также:  Подготовленные запросы php mysql

From official docs

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
  • About Long.valueOf returning a direct Wrapper object without creating new Long object is a false statement , as according to internally use of Long.parseLong (which returns a primitive long) , the primitive output of Long.parseLong will be converted to Wrapper object using by creating new object of Long class hence you wanna use direct Boxing or can call Long.valueOf=>Long.parseLong=>new Long

A little more about caching(if pass value is long) :

Cache is little helpful when you want to use == for equality check (like intern strings) with Object type. Long cache will only keep a static array of objects who’s value is between -128 to 127 range inclusive so if your number is outside this range then you won’t be able to use == operator for equality check (you don’t believe, try following 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); 
false false true true true 

So try to use equals for equality check.

Why cache required: because number between -128 to 127 inclusive need to be given identity for performance reasons of JLS (5.1.7) so cache is not for time/space efficiency in this case.

public static Long valueOf(long l) < final int offset = 128; if (l >= -128 && l return new Long(l); > 
  • Use Long.parseLong .
  • Must use equals while working with Wrapper classes.
  • Cache for java mechanism works only if you want to use numbers between -128 to 127 with Wrapper classes.

Источник

How to convert String to long in Java?

I got a simple question in Java: How can I convert a String that was obtained by Long.toString() to long ?

Читайте также:  Кликнуть на кнопку php

10 Answers 10

 Long.parseLong("0", 10) // returns 0L Long.parseLong("473", 10) // returns 473L Long.parseLong("-0", 10) // returns 0L Long.parseLong("-FF", 16) // returns -255L Long.parseLong("1100110", 2) // returns 102L Long.parseLong("99", 8) // throws a NumberFormatException Long.parseLong("Hazelnut", 10) // throws a NumberFormatException Long.parseLong("Hazelnut", 36) // returns 1356099454469L Long.parseLong("999") // returns 999L 

To convert a String to a Long (object), use Long.valueOf(String s).longValue();

@MikeDaniels, Because this is a very indirect way of doing it. See docs.oracle.com/javase/7/docs/api/java/lang/…, it returns a Long object not the primitive long.

Long.valueOf(String s) gives a Long (object) and Long.valueOf(String s).longValue() gives the long (primitive).

public class StringToLong < public static void main (String[] args) < // String s = "fred"; // do this if you want an exception String s = "100"; try < long l = Long.parseLong(s); System.out.println("long l = " + l); >catch (NumberFormatException nfe) < System.out.println("NumberFormatException: " + nfe.getMessage()); >> > 

Long.valueOf(String s) — obviously due care must be taken to protect against non-numbers if that is possible in your code.

There are a few ways to convert String to long :

String numberAsString = "1234"; long number = Long.valueOf(numberAsString).longValue(); 
String numberAsString = "1234"; Long longObject = new Long(numberAsString); long number = longObject.longValue(); 

We can shorten to:

String numberAsString = "1234"; long number = new Long(numberAsString).longValue(); 
long number = new Long("1234").longValue(); 
String numberAsString = "1234"; DecimalFormat decimalFormat = new DecimalFormat("#"); try < long number = decimalFormat.parse(numberAsString).longValue(); System.out.println("The number is: " + number); >catch (ParseException e)

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.

Thanks to auto-unboxing allowing to convert a wrapper class’s instance into its corresponding primitive type, the code would then be:

Please note that the previous code can still throw a NumberFormatException if the provided String doesn’t match with a signed long .

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.

Источник

Оцените статью