Table of contents
1.
Introduction
2.
Methods to Convert String to Long
2.1.
Using the parseLong() method of the Long class:
2.1.1.
Syntax : 
2.1.2.
Example :
2.2.
Using valueOf() method of Long class
2.2.1.
Here's the syntax of the valueOf() method:
2.2.2.
For example : 
2.3.
Using the constructor of the Long class
2.3.1.
Syntax
2.3.2.
Example
3.
Frequently Asked Questions
3.1.
What happens if the string contains non-numeric characters?
3.2.
Can we convert a string representing a decimal number to a long?
3.3.
Is there a performance difference between the methods?
4.
Conclusion
Last Updated: Jul 30, 2024
Easy

How to Convert String to Long in Java

Author Rahul Singh
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Converting a string to a long is a common task in Java programming. It allows us to take a numeric value represented as a string and convert it into a long integer that we can use for calculations or comparisons. T

How to Convert String to Long in Java

This article will explain the different methods to accomplish this conversion. We'll learn this conversion using different methods like the parseLong() method, the valueOf() method, and the constructor of the Long class. 

Methods to Convert String to Long

Using the parseLong() method of the Long class:

The parseLong() method is a convenient way to convert a string to a long. It is a static method provided by the Long class. Here's an example of how to use it:

 

Syntax : 

long parseLong(String s)


Example :

String str = "9876543210";
try {
    long num = Long.parseLong(str);
    System.out.println("Converted long: " + num);
} catch (NumberFormatException e) {
    System.out.println("Invalid string format for long: " + str);
}


In this example:

  1. We have a string "9876543210" stored in the variable str.
     
  2. We use a try-catch block to handle any potential NumberFormatException that may occur during the conversion process.
     
  3. Inside the try block, we pass the string str to the Long.parseLong() method. This method parses the string and returns the corresponding primitive long value. We assign this value to the variable num.
     
  4. Finally, we print the converted long value using System.out.println().
     
  5. If the string cannot be parsed as a long (e.g., if it contains non-numeric characters), a NumberFormatException will be thrown. The catch block will catch this exception and print an appropriate error message, indicating that the string format is invalid for a long.
     

The parseLong() method provides a direct way to convert a string to a primitive long value without the need for creating a Long object explicitly.
 

If the string cannot be parsed as a long (e.g., if it contains non-numeric characters), a NumberFormatException will be thrown. The catch block will catch this exception and print an appropriate error message, indicating that the string format is invalid for a long.

Using valueOf() method of Long class

The valueOf() method is a static method in the Long class that takes a string as input and returns a Long object representing the string's value. It is used to convert a string to a Long object.

Here's the syntax of the valueOf() method:

public static Long valueOf(String s) throws NumberFormatException


The valueOf() method takes a string parameter `s` and returns a Long object. If the string cannot be parsed as a Long, it throws a NumberFormatException.

For example : 

String str = "1234567890";
try {
    Long longObj = Long.valueOf(str);
    long num = longObj.longValue();
    System.out.println("Converted long: " + num);
} catch (NumberFormatException e) {
    System.out.println("Invalid string format for Long: " + str);
}


In this example:

1. We have a string "1234567890" stored in the variable `str`.
 

2. We use a try-catch block to handle any potential NumberFormatException that may occur during the conversion process.
 

3. Inside the try block, we pass the string `str` to the `Long.valueOf()` method. This method parses the string and returns a Long object representing the string's value. We assign this Long object to the variable `longObj`.
 

4. To get the primitive long value from the Long object, we call the `longValue()` method on `longObj` and assign the result to the variable `num`.
 

5. Finally, we print the converted long value using `System.out.println()`.
 

6. If the string cannot be parsed as a Long (e.g., if it contains non-numeric characters), a NumberFormatException will be thrown. The catch block will catch this exception and print an appropriate error message, indicating that the string format is invalid for a Long.
 

The valueOf() method provides a convenient way to convert a string to a Long object, which can be useful when working with the Long class and its methods.

Using the constructor of the Long class

The Long class provides a constructor that accepts a string as a parameter and creates a Long object representing the string's value.

Syntax

public Long(String s) throws NumberFormatException


The constructor takes a string parameter `s` and creates a new Long object. If the string cannot be parsed as a Long, it throws a NumberFormatException.

Example

String str = "5678901234";
try {
    Long longObj = new Long(str);
    long num = longObj.longValue();
    System.out.println("Converted long: " + num);
} catch (NumberFormatException e) {
    System.out.println("Invalid string format for Long: " + str);
}


In this example:

1. We have a string "5678901234" stored in the variable `str`.
 

2. We use a try-catch block to handle any potential NumberFormatException that may occur during the object creation process.
 

3. Inside the try block, we create a new instance of the Long class by passing the string `str` to its constructor. This creates a new Long object `longObj` representing the string's value.
 

4. To get the primitive long value from the Long object, we call the `longValue()` method on `longObj` and assign the result to the variable `num`.
 

5. Finally, we print the converted long value using `System.out.println()`.
 

6. If the string cannot be parsed as a Long (e.g., if it contains non-numeric characters), a NumberFormatException will be thrown. The catch block will catch this exception and print an appropriate error message, indicating that the string format is invalid for a Long.

Frequently Asked Questions

What happens if the string contains non-numeric characters?

If the string contains non-numeric characters, attempting to convert it to a long will throw a NumberFormatException. It's important to handle this exception using a try-catch block.

Can we convert a string representing a decimal number to a long?

No, a string representing a decimal number cannot be directly converted to a long. The long data type can only store integer values. If you try to convert a string with a decimal point to a long, it will throw a NumberFormatException.

Is there a performance difference between the methods?

The parseLong() method is generally faster compared to using the valueOf() method or the Long constructor. However, the performance difference is usually negligible unless you are dealing with a large number of conversions in performance-critical scenarios.

Conclusion

In this article, we discussed different methods to convert a string to a long in Java. We learned how to use the parseLong() method, the valueOf() method, and the constructor of the Long class. Each method has its own syntax and usage. These methods provide flexibility in converting strings to longs but side by side we also need to handle a few exceptions, such as NumberFormatException, when dealing with invalid string formats. 

You can also practice coding questions commonly asked in interviews on Coding Ninjas Code360

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass