Java 程序将字符串类型变量转换为 int
要理解此示例,您应该具备以下 Java 编程的知识:
示例 1:使用 parseInt() 将字符串转换为 int
public 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
值。否则编译器会抛出异常。例如,
public class Main {
public static void main(String[] args) {
// create a string variable
String str1 = "abcd";
// convert string to int
// using parseInt()
int num1 = Integer.parseInt(str1);
// print int values
System.out.println(num1); // 抛出异常 NumberFormatException
}
}
示例 2:使用 valueOf() 将字符串转换为 int
我们也可以使用该 valueOf()
方法将字符串变量转换为 Integer
对象。例如,
public 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 中称为拆箱。要了解更多信息,请访问Java 自动装箱和拆箱。
也就是,
// valueOf() returns object of Integer
// object is converted onto int
int num1 = Integer obj = Integer.valueOf(str1)