Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert String to long in Java?

Tags:

java

string

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

like image 974
Belgi Avatar asked Oct 07 '11 22:10

Belgi


People also ask

How do I convert a String to long?

There are many methods for converting a String to a Long data type in Java which are as follows: Using the parseLong() method of the Long class. Using valueOf() method of long class. Using constructor of Long class.

Can we typecast long to String?

We can convert long to String in java using String. valueOf() and Long. toString() methods.


2 Answers

Use Long.parseLong()

 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
like image 69
Mike Christensen Avatar answered Oct 17 '22 14:10

Mike Christensen


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

See link

like image 151
coreyspitzer Avatar answered Oct 17 '22 15:10

coreyspitzer