Java String to long With Examples

Java String to long conversion can be done by many ways. Today we will look into some common ways to convert java string to long primitive data type or Long object. Note that since java supports autoboxing, long primitive type and Long object can be used interchangeably without any issues.

Java String to Long

Let’s look at all the different ways to convert string to long in java.

  1. 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 throw NumberFormatException. 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.

  2. 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.

  3. 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 use parseLong() or valueOf() methods.

  4. 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:

    Note that parse() method returns instance of Number, so we are calling longValue() 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.

That’s all for converting string to long in java program.

Reference: Long API Doc

By admin

Leave a Reply

%d bloggers like this: