Languages
[Edit]
EN

Java - convert int to String

7 points
Created by:
Brett4
405

In Java, we can convert int to String in couple of different ways.

Short solutions:

// solution 1
String str1 = String.valueOf(123); // 123

// solution 2
String str2 = Integer.toString(123); // 123

// solution 3
String str3 = "" + 123; // 123

1. Using String.valueOf()

public class Example1 {

    public static void main(String[] args) {
        int num = 123;
        String str = String.valueOf(num);
        System.out.println(str); // 123
    }
}

Output:

123

2. Using Integer.toString()

public class Example2 {

    public static void main(String[] args) {
        int num = 123;
        String str = Integer.toString(num);
        System.out.println(str); // 123
    }
}

Output:

123

3. Using "" + 123

public class Example3 {

    public static void main(String[] args) {
        int num = 123;
        String str = "" + num;
        System.out.println(str); // 123
    }
}

Output:

123

4. Using String.format()

public class Example4 {

    public static void main(String[] args) {
        int num = 123;
        String str = String.format("%d", num);
        System.out.println(str); // 123
    }
}

Output:

123

5. Using StringBuilder

public class Example5 {

    public static void main(String[] args) {
        int num = 123;
        StringBuilder sb = new StringBuilder();
        sb.append(num);
        String str = sb.toString();
        System.out.println(str); // 123
    }
}

Output:

123

The same can be applied to StringBuffer

6. Using DecimalFormat

import java.text.DecimalFormat;

public class Example6 {

    public static void main(String[] args) {
        int num = 123;
        DecimalFormat df = new DecimalFormat("#");
        String str = df.format(num);
        System.out.println(str); // 123
    }
}

Output:

123

7. Using DecimalFormat with floating point pattern

import java.text.DecimalFormat;

public class Example7 {

    public static void main(String[] args) {
        int num = 12345;
        DecimalFormat df = new DecimalFormat("#,##0");
        String str = df.format(num);
        System.out.println(str); // 12,345
    }
}

Output:

12,345

References

  1. Integer.toString(int)
  2. String.valueOf(int)
  3. String.format(java.lang.String,java.lang.Object...)
  4. StringBuilder.append(int)
  5. DecimalFormat.format(long)
  6. Type conversion - wik

Post summary image

Java - convert int to String - Post summary image - dirask.com - https://dirask.com/q/X13b9j

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java conversion

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join