Java Program to Convert String to Long
Last Updated :
04 Aug, 2023
In this article, we will be performing String to Long Conversion with different methods.
Illustration of the Conversion String to Long
Input : String = “20”
Output : 20
Input : String = “999999999999”
Output : 999999999999
Methods to Convert String to Long
There are many methods for converting a String to a Long data type in Java which are as follows:
- Using the parseLong() method of the Long class
- Using valueOf() method of long class
- Using the constructor of the Long class
1. Using Long.parseLong() method of Long Class
Long.parseLong() method is a method in which all the characters in the String must be digits except the first character, which can be a digit or a minus ‘-‘.
Syntax
Long varLong=Long.parseLong(str);
Java Program to Convert String to Long using Long.parseLong() Method
Java
public class GFG {
public static void main(String args[])
{
String str = "999999999999" ;
System.out.println( "String - " + str);
long varLong = Long.parseLong(str);
System.out.println( "Long - " + varLong);
}
}
|
Output
String - 999999999999
Long - 999999999999
2. Using valueOf() Method of Long Class
The valueOf() method of the Long class is a method that converts the String to a long value. Similar to parseLong(String) method, this method also allows minus ‘-‘ as a first character in the String.
Syntax
long varLong = Long.valueOf(str);
Java Program to Convert String to Long using Long.valueOf() Method
Java
public class GFG {
public static void main(String args[])
{
String str = "999999999999" ;
System.out.println( "String - " + str);
long varLong = Long.valueOf(str);
System.out.println( "Long - " + varLong);
}
}
|
Output
String - 999999999999
Long - 999999999999
3. Using Constructor of Long Class
The Long class has a constructor which allows the String argument and creates a new Long object representing the specified string in the equivalent long value.
Java Program to Convert String to Long using Constructor of Long Class
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
String str = "999999999" ;
System.out.println( "String - " + str);
long num = new Long(str);
System.out.println( "Long - " + num);
}
}
|
Output
Share your thoughts in the comments
Please Login to comment...