十七、String 与其他类型的转换

1 String 转换为 int

String 字符串转整型 int 有以下两种方式:

  • Integer.parseInt(str)

  • Integer.valueOf(str).intValue()

注意:Integer 是一个类,是 int 基本数据类型的封装类。

例如下面代码所示:

public static void main(String[] args) {
    String str = "123";
    int n = 0;

    // 第一种转换方法:Integer.parseInt(str)
    n = Integer.parseInt(str);
    System.out.println(n);

    // 第二种转换方法:Integer.valueOf(str).intValue()
    n = 0;
    n = Integer.valueOf(str).intValue();
    System.out.println(n);
}

在 String 转换 int 时,String 的值一定是整数,否则会报数字转换异常(java.lang.NumberFormatException)。

2 int 转换为 String

整型 intString 字符串类型有以下 3 种方法:

  • String s = String.valueOf(i);

  • String s = Integer.toString(i);

  • String s = "" + i;

例如下面代码所示:

public static void main(String[] args) {
    int num = 10;

    // 第一种方法:String.valueOf(i);
    num = 10;
    String str = String.valueOf(num);
    System.out.println("str:" + str);

    // 第二种方法:Integer.toString(i);
    num = 10;
    String str2 = Integer.toString(num);
    System.out.println("str2:" + str2);

    // 第三种方法:"" + i;
    String str3 = num + "";
    System.out.println("str3:" + str3);
}

使用第三种方法相对第一第二种耗时比较大。在使用第一种 valueOf() 方法时,注意 valueOf 括号中的值不能为空,否则会报空指针异常(NullPointerException)。

主要参考内容来源:http://c.biancheng.net/