In Java, you can convert a String to a long using the parseLong() method of the Long class. This method parses the string and returns a long value.
1. Long.parseLong()
The Long.parseLong() method is the most common and straightforward way to convert a String to a long. If the String cannot be parsed as a valid long, it throws a NumberFormatException.
Example:
public class StringToLongExample {
public static void main(String[] args) {
String str = "1234567898765";
// Convert String to long using parseLong()
long num = Long.parseLong(str);
System.out.println("Converted long: " + num);
}
}
Output: Converted long: 1234567898765
Explanation:
1. Long.parseLong(str) converts the string str to a long.
2. If the string is not a valid representation of a long (e.g., contains non-numeric characters), it will throw a NumberFormatException.
2. Using Long.valueOf()
Another way to convert a String to a long is by using Long.valueOf(). This method returns a Long object (not a primitive long), and you can then convert it to a long if needed.
Example:
public class StringToLongExample {
public static void main(String[] args) {
String str = "765987654321";
// Convert String to Long object using valueOf()
Long longObj = Long.valueOf(str);
// Convert Long object to primitive long
long num = longObj.longValue();
System.out.println("Converted long: " + num);
}
}
Output: Converted long: 765987654321
Explanation:
1. Long.valueOf(str) returns a Long object, which you can convert to a primitive long using longValue().
2. If the string is not a valid number, it will throw a NumberFormatException.
How to handle Exceptions?
Both Long.parseLong() and Long.valueOf() throw a NumberFormatException if the string cannot be converted to a valid long. You should handle this exception to avoid program crashes.
public class StringToLongExample {
public static void main(String[] args) {
String str = "abcdef"; // Invalid number string
try {
long num = Long.parseLong(str); // This will throw NumberFormatException
System.out.println("Converted long: " + num);
} catch (NumberFormatException e) {
System.out.println("Error: Invalid number format");
}
}
}
Output: Error: Invalid number format