How to convert string to long java

How to convert string to long java

How to parse String to long in Java? Example

You can also use the constructor of the Long class which accepts a String and returns a Long object, but internally it also uses the parseLong() method.

BTW, if you have just started learning Java or looking forward to learning Java from scratch, I suggest you take a look at Cay S. Horstmann’s Core Java Volume 1, 9th Edition book. You will learn most of the Java fundamentals in a quick time.

Three ways to convert String to long in Java

So it returns the same Long object for every call in this range. This is OK because Long is Immutable in Java, but it can create subtle bugs if you compare auto-boxed values using the == operator in Java, as seen in this article.

How to convert string to long java. Смотреть фото How to convert string to long java. Смотреть картинку How to convert string to long java. Картинка про How to convert string to long java. Фото How to convert string to long java

String to Long Java Example

Our program will throw NumberFormatException for that value and that’s why it is commented in source code. You can un-comment and run this program to see how it behaves.

Error while Parsing String to Long

You will get the following error when you try to parse an out of range long value as String literal using Long.parseLong() method :

same error will also come if you use Long.valueOf() to do the parsing, this also proves that valueOf() internally calls to parseLong() method for parsing String :

Important things to Remember

1. Long.valueOf() method actually calls Long.valueOf(long, radix) method which is used to parse String to long in any radix e.g. binary, octal, decimal and hexadecimal. Since more often you would like to parse decimal String to long, JDK has provided a valueOf() method just for that purpose. Here is the code snippet from java.lang.Long class :

You can see that even this method is using parseLong() method to actually convert String to long in Java, the valueOf() method is just used here to automatically convert a primitive long to a Long object.

Since Long is Immutable in Java, it’s safe to share one instance with multiple users. This is also a good example of a Flyweight design pattern. Here is the code snippet from JDK :

2) Constructor of Long class which takes a String object and return a Long object also uses parseLong() method for parsing, as shown below :

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

What is the most preferred way of converting a String to Long (the Object) in Java.

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?

How to convert string to long java. Смотреть фото How to convert string to long java. Смотреть картинку How to convert string to long java. Картинка про How to convert string to long java. Фото How to convert string to long java

How to convert string to long java. Смотреть фото How to convert string to long java. Смотреть картинку How to convert string to long java. Картинка про How to convert string to long java. Фото How to convert string to long java

5 Answers 5

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Have a close look at the return types:

Inspecting the java.lang.Long source, the cache contains the following values (Sun JDK 1.8):

Excerpt from Effective Java Item 1 written by Joshua Bloch:

How to convert string to long java. Смотреть фото How to convert string to long java. Смотреть картинку How to convert string to long java. Картинка про How to convert string to long java. Фото How to convert string to long java

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

From official docs

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)

Example:

Output:

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.

To convert a String to long in Java, we can use:

Long.parseLong()

We also can use Long.parseUnsignedLong​(. ) to make sure the long is > 0.

Long.valueOf()

The difference between valueOf(. ) and parseLong(. ) is valueOf(. ) will return a Long (wrapper class) instead of primitive long.

As you can see, implicit casting automatically unbox Long into long.

Deprecated: Long‘s Constructor

It is rarely appropriate to use this constructor. Use parseLong(String) to convert a string to a long primitive, or use valueOf(String) to convert a string to a Long object.

Long.decode()

static Long decode​(String nm): Decodes a String into a Long.

DecimalFormat.parse()

parse​(String source) throws ParseException: Parses text from the beginning of the given string to produce a number. The method may not use the entire text of the given string.

Since parse() method returns instance of Number, we need to call longValue() to get the long primitive value from it. The Number also has intValue() to get int primitive value, doubleValue() for double, etc.

And similar to Convert String to int, we also can use external libraries like Apache Commons NumberUtils, Spring’s NumberUtils, and Google’s Guava primitive Longs.

Apache Commons NumberUtils

Spring NumberUtils

Similar like in Converting String to int, we can use Spring’s NumberUtils to parse String to number (in this case long).

Google Guava Longs.tryParse()

The conversion also can be done using Guava’s Longs.tryParse().

Liked this Tutorial? Share it on Social media!

How do I convert a String to an int in Java?

How to convert string to long java. Смотреть фото How to convert string to long java. Смотреть картинку How to convert string to long java. Картинка про How to convert string to long java. Фото How to convert string to long java

47 Answers 47

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

The two main ways to do this are using the method valueOf() and method parseInt() of the Integer class.

Suppose you are given a String like this

Then you can convert it into integer by using

And alternatively, you can use

But the thing here is, the method Integer.valueOf() has the following implementation in Integer class:

How to convert string to long java. Смотреть фото How to convert string to long java. Смотреть картинку How to convert string to long java. Картинка про How to convert string to long java. Фото How to convert string to long java

How to convert string to long java. Смотреть фото How to convert string to long java. Смотреть картинку How to convert string to long java. Картинка про How to convert string to long java. Фото How to convert string to long java

Convert a string to an integer with the parseInt method of the Java Integer class. The parseInt method is to convert the String to an int and throws a NumberFormatException if the string cannot be converted to an int type.

Overlooking the exception it can throw, use this:

For example, Java String to int conversion method, control for a possible NumberFormatException

How to convert string to long java. Смотреть фото How to convert string to long java. Смотреть картинку How to convert string to long java. Картинка про How to convert string to long java. Фото How to convert string to long java

Try this code with different inputs of String :

How to convert string to long java. Смотреть фото How to convert string to long java. Смотреть картинку How to convert string to long java. Картинка про How to convert string to long java. Фото How to convert string to long java

How to convert string to long java. Смотреть фото How to convert string to long java. Смотреть картинку How to convert string to long java. Картинка про How to convert string to long java. Фото How to convert string to long java

By using this method you can avoid errors.

You can have your own implementations for this, like:

How to convert string to long java. Смотреть фото How to convert string to long java. Смотреть картинку How to convert string to long java. Картинка про How to convert string to long java. Фото How to convert string to long java

How to convert string to long java. Смотреть фото How to convert string to long java. Смотреть картинку How to convert string to long java. Картинка про How to convert string to long java. Фото How to convert string to long java

There are different ways of converting a string int value into an Integer data type value. You need to handle NumberFormatException for the string value issue.

Using Java 8 Optional API

How to convert string to long java. Смотреть фото How to convert string to long java. Смотреть картинку How to convert string to long java. Картинка про How to convert string to long java. Фото How to convert string to long java

Custom algorithm:

Another solution:

(Use the string charAt method instead of convert string to byte array)

Examples:

How to convert string to long java. Смотреть фото How to convert string to long java. Смотреть картинку How to convert string to long java. Картинка про How to convert string to long java. Фото How to convert string to long java

Use this method:

How to convert string to long java. Смотреть фото How to convert string to long java. Смотреть картинку How to convert string to long java. Картинка про How to convert string to long java. Фото How to convert string to long java

I wrote this fast method to parse a string input into int or long. It is faster than the current JDK 11 Integer.parseInt or Long.parseLong. Although, you only asked for int, I also included the long parser. The code parser below requires that the parser’s method must be small for it to operate quickly. An alternative version is below the test code. The alternative version is pretty quick and it does not depend on the size of the class.

This class checks for overflow, and you could customize the code to adapt to your needs. An empty string will yield 0 with my method but that is intentional. You can change that to adapt your case or use as is.

This is only the part of the class where parseInt and parseLong are needed. Note that this only deals with base 10 numbers.

The test code for the int parser is below the code below.

Test Code Section. This should take around 200 seconds or so.

An alternative method which is also very fast. Note that array of int pow is not used, but a mathematical optimization of multiply by 10 by bit shifting.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *