将字符串转换为长整型的Java程序
给定一个 String,任务是在Java中将其转换为 Long。
例子:
Input : String = "20"
Output: 20
Input : String = "999999999999"
Output: 999999999999
我们可以使用各种方法来执行任务:
A. 使用 Long.parseLong()
句法:
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);
}
}
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);
}
}
输出
999999999999
B. 使用 Long.valueOf()
句法:
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);
}
}
输出
999999999999