Skip to content
Related Articles

Related Articles

Improve Article

Java Program to Convert String to Long

  • Difficulty Level : Expert
  • Last Updated : 11 Nov, 2020

Given a String, the task is to convert it into Long in Java.

Examples:

Input : String = "20"
Output: 20

Input : String = "999999999999"
Output: 999999999999

We can use various methods to perform the task :

A. Using Long.parseLong()

Syntax:



Long varLong=Long.parseLong(str);

Java




// Java program to convert String to Long 
// using parseLong() 
    
public class GFG { 
    
    // main method 
    public static void main(String args[]) 
    
    
        // create a String 
        String str = "999999999999"
    
        // convert into Long 
        long varLong = Long.parseLong(str); 
    
        // print String as Long 
        System.out.println(varLong); 
    
}
Output
999999999999

B. Using Long.valueOf()

Syntax:

long varLong = Long.valueOf(str);

Java




// Java program to convert String to Long
// using valueOf() 
    
public class GFG { 
    
    // main method 
    public static void main(String args[]) 
    
    
        // create a String 
        String str = "999999999999"
    
        // convert into Long
        long varLong = Long.valueOf(str); 
    
        // print String as Long
        System.out.println(varLong); 
    
}
Output
999999999999

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :