欢迎访问宙启技术站
智能推送

Java字符串转int:将字符串转换为整数型变量。

发布时间:2023-07-03 02:40:14

在Java中,可以使用Integer.parseInt()方法将字符串转换为整数型变量。以下是使用Integer.parseInt()方法的示例代码:

String strNum = "12345";
int num = Integer.parseInt(strNum);
System.out.println(num);  // 输出:12345

在上述示例中,将字符串"12345"转换为整数型变量num,并打印输出。需要注意的是,被转换的字符串必须是有效的整数值,如果字符串包含非数字字符或者超出了整数的表示范围,将会抛出NumberFormatException异常。因此,在转换前 对字符串进行合法性检查或者使用try-catch块捕获异常。

另外,还可以使用Integer.valueOf()方法将字符串转换为Integer对象,然后通过调用intValue()方法获取整数值。以下是使用Integer.valueOf()方法的示例代码:

String strNum = "12345";
Integer num = Integer.valueOf(strNum);
System.out.println(num.intValue());  // 输出:12345

使用Integer.valueOf()方法的好处是,如果字符串的值在缓存范围内(-128到127),则返回缓存中的Integer对象,而不是创建新的对象,从而提高了性能。

总结而言,Java字符串转换为整数型变量可以使用Integer.parseInt()方法或Integer.valueOf()方法。