Java
Programming
Data Conversion
String
Long Data Type

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.

Browse interview questions

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:

java
1String numberStr = "123456789";
2try {
3    long number = Long.parseLong(numberStr);
4    System.out.println("The number is: " + number);
5} catch (NumberFormatException e) {
6    System.out.println("Invalid string to convert to long.");
7}

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:

java
1String numberStr = "987654321";
2try {
3    Long number = Long.valueOf(numberStr);
4    System.out.println("The number is: " + number);
5} catch (NumberFormatException e) {
6    System.out.println("Invalid string to convert to long.");
7}

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:

java
1import java.text.DecimalFormat;
2import java.text.ParseException;
3
4String numberStr = "1,234,567,890";
5DecimalFormat format = new DecimalFormat("#,###");
6
7try {
8    Number number = format.parse(numberStr);
9    long longValue = number.longValue();
10    System.out.println("The number is: " + longValue);
11} catch (ParseException e) {
12    System.out.println("Error parsing number.");
13}

Summary Table

MethodReturn TypeThrows ExceptionUse Case
Long.parseLong()longNumberFormatExceptionSimple string without formatting.
Long.valueOf()LongNumberFormatExceptionNeeds an object, not primitive.
DecimalFormat.parse()NumberParseExceptionComplex 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 NullPointerException in Long.parseLong() and Long.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
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track 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.

Browse interview questions

All Rights Reserved.