在Java开发中,字符串和数值类型的相互转换是非常常见的操作,尤其是字符串转数值类型的场景,比如解析配置文件里的数字参数、处理前端传递的表单数值等。不同的数值类型对应不同的转换方式,使用时需要选对方法才能保证程序稳定运行。

整型转换方法
最常用的是将字符串转为int类型,对应使用Integer类的parseInt方法,这个方法会返回对应的基本类型int值。
public class StringToIntDemo {
public static void main(String[] args) {
String numStr = "123";
// 使用Integer.parseInt将字符串转为int类型
int num = Integer.parseInt(numStr);
System.out.println("转换后的数值为:" + num);
// 如果要转为Integer包装类,可以使用valueOf方法
Integer numObj = Integer.valueOf(numStr);
System.out.println("包装类数值为:" + numObj);
}
}如果需要转换为long类型,使用Long类的parseLong方法,short和byte类型也可以类似处理,不过实际开发中short和byte的转换场景相对较少。
浮点型转换方法
字符串转浮点型时,对应double类型使用Double.parseDouble方法,float类型使用Float.parseFloat方法,用法和整型的转换逻辑一致。
public class StringToFloatDemo {
public static void main(String[] args) {
String doubleStr = "123.45";
// 转为double基本类型
double doubleNum = Double.parseDouble(doubleStr);
System.out.println("double数值为:" + doubleNum);
String floatStr = "67.89";
// 转为float基本类型
float floatNum = Float.parseFloat(floatStr);
System.out.println("float数值为:" + floatNum);
}
}转换时的异常处理
如果字符串的内容不符合数值格式,比如字符串是"abc"或者"123.4a",调用上述转换方法时会抛出NumberFormatException异常,因此实际开发中通常需要捕获这个异常,避免程序崩溃。
public class StringConvertDemo {
public static void main(String[] args) {
String errorStr = "abc123";
try {
int num = Integer.parseInt(errorStr);
System.out.println("转换结果:" + num);
} catch (NumberFormatException e) {
System.out.println("字符串格式不正确,无法转换为数值类型");
e.printStackTrace();
}
}
}注意事项
- 转换的字符串内容必须是合法的数值格式,不能包含非数字字符,除了正负号和浮点型的小数点。
- 如果使用
Integer.parseInt转换超出int范围的字符串,也会抛出NumberFormatException,此时可以考虑转为long类型。 valueOf方法返回的是包装类对象,而parseXxx方法返回的是基本类型,根据开发需求选择对应的方法即可。