基本类型与字符串之间的转换

基本类型与字符串之间的转换

1.基本类型-->字符串(String)

  1. 基本类型的值+" " 最简单的方法(工作中常用)

  2. 包装类的静态方法toString(参数),不是Object类的toString方法()重载

    static String toString(int i)返回一个表示指定整数的string 对象。

  3. String类的静态方法valueOf(参数)

    static String valueOf(int i)返回 int 参数的字符串表示形式。

2.字符串(String)--> 基本类型

使用包装类的静态方法parseXXX("字符串");

如:

​ Integer类: static int parseInt(Sting s)

​ Double类:static double parseDouble(String s);

 public static void main(String[] args) {
        // 基本类型-->字符串
        int i1 = 100;
        String s1 = i1 +"";
        System.out.println(s1+999);

        String s2 = Integer.toString(100);
        System.out.println(s2+300);

        String s3 = String.valueOf(100);
        System.out.println(s3 + 100);

        // 字符串(String)--> 基本类型
        int i = Integer.parseInt(s1);
        System.out.println(i - 10);

        // 不能转换字符串报错 数字格式异常 NumberFormatException
        /*int a = Integer.parseInt("a");
        System.out.println(a);*/

    }
原文地址:https://www.cnblogs.com/anke-z/p/12507176.html