A String can be converted into a long in Java using methods provided by the Long wrapper class. This conversion is useful when a numeric value is received as text and needs to be used for arithmetic or other numeric operations.
- Invalid numeric strings cause NumberFormatException.
- The input must be within the valid range of the long data type.
Illustration
Input:
"999999999999"
Output:999999999999
Methods to Convert String to Long
1. Long.valueOf()
Converts a String into a Long object representing the numeric value.
Syntax
long varLong = Long.valueOf(str);
public class GFG {
public static void main(String args[])
{
// Creating custom string
String s = "999999999999";
// Printing the above string
System.out.println("String - " + s);
// Converting into Long data type
long l = Long.valueOf(s);
// Printing String as Long
System.out.println("Long - " + l);
}
}
Output
String - 999999999999 Long - 999999999999
Explanation: Long.valueOf() parses the string and returns a Long object. Java can automatically unbox this object to a primitive long when required. Like parseLong(), it supports a leading - sign and throws NumberFormatException for invalid input.
2. Long.parseLong()
Converts a String into a primitive long value.
Syntax:
long value = Long.parseLong(str);
public class Main {
public static void main(String[] args) {
String str = "999999999999";
long value = Long.parseLong(str);
System.out.println("String: " + str);
System.out.println("Long: " + value);
}
}
Output
String: 999999999999 Long: 999999999999
Explanation: The Long.parseLong(str) method converts the numeric String "999999999999" into a primitive long value. The converted value is then stored in the value variable and printed.