Open In App

How to Convert a String to an Long in Java ?

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, String to Integer Conversion is not always effective as the size of the String can overpass Integer. In this article, we will learn the method provided by the Long class or by using the constructor of the Long class.

Example of String to Long Conversion

Input: " 9876543210"
Output: 9876543210

Program Convert String to Long in Java

The Most basic method we can come up with to convert String to Long in Java is using Constructor:

Java




// Java Program to Convert String to Long
// Using Constructor of Long class
import java.io.*;
import java.util.*;
  
// Driver Class
class GFG {
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String str = "9876543210";
        System.out.println("String : " + str);
  
        // Converting above string to long
        // using Long(String s) constructor
        Long num = new Long(str);
  
        // Printing the above long value
        System.out.println("Long : " + num);
    }
}


Output

String : 9876543210
Long : 9876543210

Explanation of the above program:

  • String str is the String which we want to Convert to Long.
  • String str size can be short as Short Integer or Long as Long Integer.
  • Long object num is initiated and the string value is passed as parameter.
  • String Object value is now passed to Long Integer which has now the same value that of Integer.
  • Now we get the result num.

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads