在程序开发中,我们经常需要将基本数据类型转成 String 类型,或者将 String 类型转成基本数据类型。
基本数据类型 => String 类型:将基本数据类型的值 + “” 即可
String 类型 => 基本数据类型:通过基本类型的包装类调用 parseXX 方法即可。
下面几点需要注意:
- 在将 String 类型转成基本数据类型时,要确保 String 类型能够转成有效的数据,如果格式不正确,就会抛出异常,程序就会终止,这个问题在后面讲异常处理时会提到。
- char 和 String 的转换是例外,不能使用
public class Main {public static void main(String[] args) {// 基本数据类型 => Stringint i1 = 100;float f1 = 100.5F;double d1 = 100.5;boolean b1 = true;char c1 = 'A';String s1 = i1 + "";String s2 = f1 + "";String s3 = d1 + "";String s4 = b1 + "";String s5 = c1 + "";System.out.println(s1); // 100System.out.println(s2); // 100.5System.out.println(s3); // 100.5System.out.println(s4); // trueSystem.out.println(s5); // A// String => 基本数据类型int i2 = Integer.parseInt(s1);float f2 = Float.parseFloat(s2);double d2 = Double.parseDouble(s3);boolean b2 = Boolean.parseBoolean(s4);char c2 = s5.charAt(0);// 取字符串的首个字符System.out.println(i2); // 100System.out.println(f2); // 100.5System.out.println(d2); // 100.5System.out.println(b2); // trueSystem.out.println(c2); // A// 异常情况String str = "hello";int i3 = Integer.parseInt(str); // 能通过编译,但运行时会报错:java.lang.NumberFormatException: For input string: "hello"}}
