Java 类型转换方法

Java 字符串转为int类型是开发中常用的需求,它有3种方法。

下面介绍每种方法的使用。

方法1

它有拆箱的过程,其语法为

public static Integer valueOf(String s) throws NumberFormatException

推荐使用方法2或者方法3。

public class String2IntExample1{
    public static void main(String[] args) {
        String a = "2";
        String b = "3";
        int c = Integer.parseInt(a) + Integer.parseInt(b);
        System.out.println("不转int类型c=" + a+b);//字符串拼接
        System.out.println("转为int类型c=" + c);//数学计算

    }
} 
输出:
不转int类型c=23
转为int类型c=5

 方法2

使用Integer.valueOf(String str).intValue()

public class String2IntExample2{
    public static void main(String[] args) {
        String a = "2";
        String b = "3";
        int c = Integer.valueOf(a).intValue() + Integer.valueOf(b).intValue();
        System.out.println("不转int类型c=" + a+b);//字符串拼接
        System.out.println("转为int类型c=" + c);//数学计算

    }
} 

输出:

不转int类型c=23
转为int类型c=5

方法3

使用 ASCII 码的方法

public class String2IntExample3{
    public static void main(String[] args) {
        String a = "2";
        String b = "3";
        int c = string2int(a) + string2int(b);
        System.out.println("不转int类型c=" + a+b);//字符串拼接
        System.out.println("转为int类型c=" + c);//数学计算
    }

    public static int string2int(String s) {
        int num = 0;
        int pos = 1;
        for (int i = s.length() - 1; i >= 0; i--) {
            num += (s.charAt(i) - '0') * pos;
            pos *= 10;

        }
        return num;

    }

} 

输出:

不转int类型c=23
转为int类型c=5