How to convert String to long in Java?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
In Java, converting a string to a long (a 64-bit integer value) is a common operation, especially when dealing with applications that require processing numerical data stored as text, such as reading numbers from a file or user input. There are several ways to achieve this, each with its specific use cases and potential pitfalls. In this article, we'll explore how to convert a string to a long in Java using various methods and some important considerations.
Using Long.parseLong()
The most straightforward method to convert a string to a long is by using the Long.parseLong() method. This method throws a NumberFormatException if the string cannot be parsed as a long. It's crucial to handle or declare this exception when using this method.
Example:
Using Long.valueOf()
Another common approach is using the Long.valueOf() method. This method also throws NumberFormatException if the string does not contain a parsable long. Unlike Long.parseLong(), which returns a primitive long, Long.valueOf() returns a Long object. This can be useful if you want to store the result in collections that can only hold objects.
Example:
Handling Min and Max Values
When converting strings to long, it's important to consider the range of long in Java. The value must be between Long.MIN_VALUE and Long.MAX_VALUE ($-2^{63}$ to $2^{63}-1$). If the parsed value exceeds these limits, a NumberFormatException will be thrown.
Using DecimalFormat.parse()
For more complex string formats that include number groupings, decimals, or special characters (such as currency symbols), DecimalFormat from the java.text package can be used. This class allows for customized numerical formats and can handle strings that Long.parseLong() and Long.valueOf() cannot, as long as the number itself is within the range for a long.
Example:
Summary Table
| Method | Return Type | Throws Exception | Use Case |
Long.parseLong() | long | NumberFormatException | Simple string without formatting. |
Long.valueOf() | Long | NumberFormatException | Needs an object, not primitive. |
DecimalFormat.parse() | Number | ParseException | Complex formats, like numbers with commas or currency. |
Additional Considerations
- Null Safety: Ensure the string is not null before attempting to parse it. Null inputs will cause
NullPointerExceptioninLong.parseLong()andLong.valueOf(). - Performance: For parsing large numbers of strings, consider the performance differences. Direct parsing methods like
Long.parseLong()are typically faster than creating objects or using formatters. - Use in Collections: If the value needs to be used in a generic collection,
Long.valueOf()might be preferable, since collections store objects.
Conclusion
Converting strings to long in Java requires understanding the nature of the string input and choosing the appropriate method. Exception handling is crucial to prevent runtime errors when faced with unparseable strings. Whether you choose direct parsing for performance or utilize more flexible formatting options depends on the specific requirements of your application.
Related reading
- How to convert Strings to and from UTF8 byte arrays in Java
- How to convert UTF-8 byte to string
- How to convert/parse from String to char in java?
- How to cope with x-forwarded-headers in Spring Boot 2.2.0? Spring Web MVC behind reverse proxy
- How to copy a java.util.List into another java.util.List
- How to count lines of Java code using IntelliJ IDEA?
- How to create a bean using Bean annotation in Spring Boot for abstract class?
- How to create a custom exception type in Java?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.