示例 1:使用 parseInt() 将字符串转换为 int 的 Java 程序
class Main {
public static void main(String[] args) {
// create string variables
String str1 = "23";
String str2 = "4566";
// convert string to int
// using parseInt()
int num1 = Integer.parseInt(str1);
int num2 = Integer.parseInt(str2);
// print int values
System.out.println(num1); // 23
System.out.println(num2); // 4566
}
}
在上面的示例中,我们使用了 Integer
类中的 parseInt()
方法将字符串变量转换为 int
。
在这里,Integer
是 Java 中的一个包装类。要了解更多信息,请访问 Java 包装类。
注意:字符串变量应代表 int
值。否则,编译器将抛出 异常。例如,
class Main {
public static void main(String[] args) {
// create a string variable
String str1 = "Programiz";
// convert string to int
// using parseInt()
int num1 = Integer.parseInt(str1);
// print int values
System.out.println(num1); // throws NumberFormatException
}
}
示例 2:使用 valueOf() 将字符串转换为 int 的 Java 程序
我们还可以使用 valueOf() 方法将字符串变量转换为 Integer
对象。例如,
class Main {
public static void main(String[] args) {
// create string variables
String str1 = "643";
String str2 = "1312";
// convert String to int
// using valueOf()
int num1 = Integer.valueOf(str1);
int num2 = Integer.valueOf(str2);
// print int values
System.out.println(num1); // 643
System.out.println(num2); // 1312
}
}
在上面的示例中,Integer
类中的 valueOf()
方法将字符串变量转换为 int
。
在这里,valueOf()
方法实际上返回一个 Integer
类的对象。但是,该对象会被自动转换为基本类型。这在 Java 中称为拆箱。
即:
// valueOf() returns object of Integer
// object is converted onto int
int num1 = Integer obj = Integer.valueOf(str1)
要了解更多信息,请访问 Java 自动装箱和拆箱。