Java String to Long
Let’s look at all the different ways to convert string to long in java.
-
Long.parseLong()
We can parse String to long using
parseLong()
method. Note that string should not contain “L” at the end as type indicator or else it will throwNumberFormatException
. However string can start with “-” to denote negative number or “+” to denote positive number. This method returns long primitive type. Below code snippet shows how to convert string to long using Long.parseLong() method.String str = "-12345"; long l = Long.parseLong(str); // returns long primitive
-
Long.valueOf()
This method works almost similar as parseLong() method, except that it returns Long object. Let’s see how to use this method to convert String to Long object.
String str = "12345"; Long l = Long.valueOf(str); // returns Long object
-
new Long(String s)
We can convert String to Long object through it’s constructor too. Also if we want long primitive type, then we can use
longValue()
method on it. Note that this constructor has been deprecated in Java 9, preferred approach is to useparseLong()
orvalueOf()
methods.String str = "987"; long l = new Long(str).longValue(); //constructor deprecated in java 9
-
DecimalFormat parse()
This is useful to parse formatted string to long. For example, if String is “1,11,111” then we can use DecimalFormat to parse this string to long as:
String str = "1,11,111"; try { long l = DecimalFormat.getNumberInstance().parse(str).longValue(); System.out.println(l); } catch (ParseException e) { e.printStackTrace(); }
Note that parse() method returns instance of
Number
, so we are callinglongValue()
to get the long primitive type from it.
Convert String to Long with Radix
Sometimes numbers are not written in decimal format, they can be in binary, octal or hexadecimal format. There are ways to convert non-decimal radix strings to long by passing radix value. Below code snippet shows how to convert string to long value for binary, octal and hexadecimal string representations.
str = "111"; // Binary format (2^2+2+1 = 7)
l = Long.parseLong(str, 2);
System.out.println(l); // prints 7
str = "0111"; // Octal format (8^2+8+1 = 73)
l = Long.parseLong(str, 8);
System.out.println(l); // prints 73
str = "FFF"; // Hexadecimal format (15*16^2+15*16+15 = 4095)
l = Long.parseLong(str, 16);
System.out.println(l); // prints 4095
That’s all for converting string to long in java program.
Reference: Long API Doc