How to convert String to long

In Java we have multiple ways to convert String to long. We will see a few of those ways in this post.

1. Convert String to long using Long.parseLong()

If the String value doesn’t contain all digits OR if the String value has all digits but exceeds the max limit that can be allowed in an Long, then during converting String to long, a NumberFormatException is thrown. So you may want to handle this exception when converting String to long.

A String can also be converted to long using a radix specified by public static long parseLong(String s,int radix)
See Examples

In the examples the 2nd param we are passing is the format of String we have received.
10 – regular
16- Hexadecimal
2- Binary

Complete Example
Lets see an example that will use both the methods to convert string to long.

Output

2. Convert String to Long using Long.valueOf()

Similar to Long.parseLong(), we can convert String to Long using Long.valueOf().
We can also convert the hexadecimals or binary values using Long.valueOf(String s,int radix)

We will see a small example.

Difference between Long.parseLong and Long.valueOf()

Long.parseLong() returns a primitive long while Long.valueOf() returns a new Long() object
Long.valueOf() internally uses Long.parseLong(), hence if you want a primitive value you should use Long.parseLong().

Other methods to Convert String to long

There are many other ways to convert string to long. Few of them are

References

1. Long API

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn