Convert Java String to Long

We often have to extract some text that is a number. To perform some operations on that number, we must first convert it to the appropriate data type. In this post, you will learn how to convert Java String to long.

The parseLong() method in Java is a static method that can be used to convert a String to a long data type.

Syntax

public static long parseLong(String s)


This method throws NumberFormatException if the String does not contain a parsable long.

For a comprehensive guide on handling such exceptions, refer to this tutorial Exception Handling in Java.

Example

class Test {

  public static void main(String[] args) {
    long l1 = Long.parseLong("18273312");
    long l2 = Long.parseLong("122911311131");
    long l3 = Long.parseLong("122213");

    System.out.println(l1);
    System.out.println(l2);
    System.out.println(l3);
  }
}
Output: 18273312 122911311131 12221
 
That’s all about how to convert String to long in Java. Proceed to the next lesson.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *