首页 > 文章列表 > Java怎么将字符串String转换为整型Int

Java怎么将字符串String转换为整型Int

java int string
425 2023-04-27

Java怎么将字符串String转换为整型Int

用法

在java中经常会遇到需要对数据进行类型转换的场景,String类型的数据转为Int类型属于比较常见的场景,主要有两种转换方法:

  • 1. 使用Integer.parseInt(String)方法

  • 2. 使用Integer.valueOf(String)方法

具体demo如下:

public void convert() {

    // 1.使用Integer.parseInt(String)

    String str1 = "31";

    Integer num1 = Integer.parseInt(str1);

    System.out.print("字符串31转换为数字:");

    System.out.println(num1);



    // 2.使用Integer.valueOf(String)

    String str2 = "32";

    Integer num2 = Integer.valueOf(str2);

    System.out.print("字符串32转换为数字:");

    System.out.println(num2);

}

执行结果:

根据执行结果可见,两种方式都能完成字符串到整型的转换。

注意点

但需要注意的是,使用这两种方法都有一个前提,那就是待转换字符串的内容必须为纯数字。 

不难发现上面demo中的待转换字符串都是"31"、"32"这种由纯数字组成的字符串,如果待转字符串中出现了除数字以外的其他字符,则程序会抛出异常。

如下demo所示,在字符串中加入小写英文字母,并用try-catch语句包裹代码段以捕捉会出现的异常。(因为我们已经知道,带字母的字符串转换为整型会出现数字格式转换的异常,所以选择catch NumberFormatException)

public void convert() {

    // 1.Integer.parseInt(String)

    try {

        String str1 = "31a";

        Integer num1 = Integer.parseInt(str1);

        System.out.print("字符串31a转换为数字:");

        System.out.println(num1);

    } catch (NumberFormatException e) {

        System.out.println("Integer.parseInt(String)方法执行异常");

        e.printStackTrace();

    }

 

    // 1.Integer.valueOf(String)

    try {

        String str2 = "32b";

        Integer num2 = Integer.valueOf(str2);

        System.out.print("字符串32b转换为数字:");

        System.out.println(num2);

    } catch (NumberFormatException e) {

        System.out.println("Integer.valueOf(String)方法执行异常");

        e.printStackTrace();

    }

}

从执行结果可见,这段代码分别在Integer.parseInt(String)方法和Integer.valueOf(String)位置触发了NumberFormatException,其原因都是被转换的字符串中存在英文字母,无法转换成整型

性能比较

我们可以通过使用System.nanoTime()来查看两种方法执行的时间差

public static void convert() {

    // 1.Integer.parseInt(String)

    String str1 = "321";

    long before1 = System.nanoTime();

    Integer.parseInt(str1);

    long interval1 = System.nanoTime() - before1;

    System.out.print("Integer.parseInt(String)的执行时长(纳秒):");

    System.out.println(interval1);



    // 1.Integer.valueOf(String)

    String str2 = "332";

    long before2 = System.nanoTime();

    Integer.valueOf(str2);

    long interval2 = System.nanoTime() - before2;

    System.out.print("Integer.valueOf(String)的执行时长(纳秒):");

    System.out.println(interval2);

}

其中,interval1和interval2的值分别指两个方法的执行前后系统时间之差,单位是纳秒,执行多次后均可发现,Integer.valueOf(String)方法的执行时长要小于Integer.parseInt(String)方法,性能更优