Java中将int变量转换为字符串的4种方法

1、valueOf()方法

String.valueOf(int i)

class Main {
  public static void main(String[] args) {

    // 创建int变量
    int num1 = 36;
    int num2 = 99;

    // 将int转换为字符串
    // 使用 valueOf()
    String str1 = String.valueOf(num1);
    String str2 = String.valueOf(num2);

    //打印字符串变量
    System.out.println(str1);    // 36
    System.out.println(str2);    // 99
  }
}

2、toString()方法

Integer.toString(int i)

class Main {
  public static void main(String[] args) {

    // 创建int变量
    int num1 = 476;
    int num2 = 78656;

    // 将int转换为字符串
    // 使用 toString()
    String str1 = Integer.toString(num1);
    String str2 = Integer.toString(num2);

    //打印字符串变量
    System.out.println(str1);    // 476
    System.out.println(str2);    // 78656
  }
}

3、+字符串连接运算符

i+""

class Main {
  public static void main(String[] args) {

    // 创建int变量
    int num1 = 3476;
    int num2 = 8656;

    //将int转换为字符串
    // using + sign
    String str1 = "" + num1;
    String str2 = "" + num2;

    //打印字符串变量
    System.out.println(str1);    // 3476
    System.out.println(str2);    // 8656
  }
}

字符串连接操作将整数转换为字符串

4、+字符串连接运算符

String.format("%d", int i)

class Main {
  public static void main(String[] args) {

    // 创建int变量
    int num = 9999;

    //使用format()将int格式化为字符串
    String str = String.format("%d", num);

    System.out.println(str);    // 9999
  }
}

效率比较

Integer.toString(int i) > String.valueOf(int i) > i+""

posted @ 2022-06-09 18:58  铁头蛙  阅读(5251)  评论(0)    收藏  举报