基本数据类型、包装类、String三者之间的转换

381 阅读1分钟

一、基本数据类型及其对应的包装类


二、基本数据类型与其对应的包装类的转换

(1)基本数据类型--->包装类:

  • 自动装箱:
    Integer i = 9;
  • 使用包装类的valueOf()方法:
    Integer I = Integer.valueOf(3);

(2)包装类--->基本数据类型

  • 自动拆箱:
    Integer I = 9;
    int i = I;
  • 使用包装类的xxxValue()方法:
    Integer I = 9;
    int i = I.intValue();

(3)基本数据类型--->String:

  • 使用连接符‘+’:
    int i = 9;
    String s = "" + i; 
  • 使用String类的valueOf()方法:
    int i = 9;
    String s = String.valueOf(i);

(4)String--->基本数据类型:

  • 调用相应包装类的parseXxx(String s)方法:
    String s = "9";
    int a = Integer.parseInt(s);

(5)包装类--->String:

  • 使用String类的valueOf()方法:
    Integer I = 9;
    String s = String.valueOf(I);
  • 调用相应包装类的对象的toString()方法:
    Integer I = 9;
    String s = I.toString();
  • 调用相应包装类的toString()方法:
    Integer I = 9;
    String s = Integer.toString(I);

(6)String--->包装类:

  • 调用相应包装类的parseXxx(String s)方法:
    String s = "9";
    Integer I = Integer.parseInt(s);

注意:String转换为基本数据类型或包装类时,如无法进行转换,会出现NumberFormatException错误。例如:

    String s = "aaaa";
    Integer I = Integer.parseInt(s);