Java Program to Convert String to Long
To convert a String to Long in Java, we can use built-in methods provided by the Long class. In this article, we will learn how to convert String to Long in Java with different methods.
Example:
In the below example, we use the most common method i.e. Long.parseLong() method to convert a string to a primitive long.
// Java Program to convert String to Long using parseLong() Method
public class GFG {
public static void main(String args[]) {
// Creating a custom string
String s = "999999999999";
System.out.println("String: " + s);
// Converting into Long
long l = Long.parseLong(s);
// Printing String as Long
System.out.println("Long: " + l);
}
}
Output
String: 999999999999 Long: 999999999999
Note: 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 of Long.parseLong() method
Long varLong = Long.parseLong(s);
Parameter:
str
: A string containing numeric characters. It can include a leading “-"
for negatives.
Return Type:
- A
long
primitive representing the numeric value of the string.
Other Methods to Convert String to Long in Java
There are many other ways to convert a String to a Long data type in Java which are as follows:
1. Using Long.valueOf() Method
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 of Long.valueOf() Method
long varLong = Long.valueOf(str);
Example:
// Java Program to Convert String to Longn using valueOf() Method
public class GFG {
public static void main(String args[])
{
// Creating custom string
String s = "999999999999";
// Printing the above string
System.out.println("String - " + s);
// Converting into Long data type
long l = Long.valueOf(s);
// Printing String as Long
System.out.println("Long - " + l);
}
}
Output
String - 999999999999 Long - 999999999999
2. 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.
Example:
// Java Program to Convert String to Long using Constructor of Long class
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Custom input string
String s = "999999999";
System.out.println("String - " + s);
// Converting above string to long
// using Long(String s) constructor
long n = new Long(s);
// Printing the above long value
System.out.println("Long - " + n);
}
}
Output
String - 999999999 Long - 999999999
Note: The Long(String s)
constructor is deprecated since Java 9. It is recommended to use Long.parseLong()
or Long.valueOf()
for converting a String
to long
.