软件编程
位置:首页>> 软件编程>> java编程>> Java将字符串String转换为整型Int的两种方式

Java将字符串String转换为整型Int的两种方式

作者:码说TM  发布时间:2021-12-11 10:01:32 

标签:Java,String,转换,int

Java 如何将String转化为Int

在 Java 中要将 String 类型转化为 int 类型时,需要使用 Integer 类中的 parseInt() 方法或者 valueOf() 方法进行转换.

例1:

String str = "123";

try {

    int a = Integer.parseInt(str);

} catch (NumberFormatException e) {

    e.printStackTrace();

}

例2:

String str = "123";

try {

    int b = Integer.valueOf(str).intValue()

} catch (NumberFormatException e) {

    e.printStackTrace();

}

在转换过程中需要注意,因为字符串中可能会出现非数字的情况,所以在转换的时候需要捕捉处理异常

附录: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);
}

        执行结果:

Java将字符串String转换为整型Int的两种方式

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

注意点

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

        不难发现上面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,其原因都是被转换的字符串中存在英文字母,无法转换成整型

Java将字符串String转换为整型Int的两种方式

性能比较

        我们可以通过查看源码来比价两个方法的性能:

public static int parseInt(String s) throws NumberFormatException {
   return parseInt(s,10);
}

public static Integer valueOf(String s) throws NumberFormatException {
   return Integer.valueOf(parseInt(s, 10));
}

        不难发现,Integer.parseInt(String) 和Integer.valueOf(String)的实现中,都是调用的一个方法:Integer.parseInt(String, Integer);但是Integer.valueOf(String)还多嵌套了一层Integer.valueOf(Integer)方法,因此从源码可得知:Integer.parseInt(String)方法的性能更胜一筹。

来源:https://blog.csdn.net/qq_33323054/article/details/126256907

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com