示例 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 Wrapper Class。
注意: 字符串变量应该代表整数值。否则编译器会抛出异常。例如,
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 中称为拆箱。要了解更多信息,请访问 Java 自动装箱和拆箱。
也就是说,
// valueOf() returns object of Integer // object is converted onto int int num1 = Integer obj = Integer.valueOf(str1)