Convert int to String in Java

In one of the previous lessons, we covered conversion from String to int. Here, you will learn how to convert int to String in Java. There are some predefined methods that we can use for that, like the following:

  • String.valueOf() method
  • Integer.toString method
  • String.format() method

Convert int to String in Java using the String.valueOf() method

There are multiple overloaded versions of the valueOf() method from the String class. We will use the one which accepts int as an argument.

Example

class Test {

  public static void main(String[] args) {

    String str = String.valueOf(32);

    System.out.println(str);

  }
}
Output: 32

Convert int to String using the Integer.toString() method

We can also use the static method toString() of the Integer class. It returns a String representation of a provided int.

class Test {

  public static void main(String[] args) {

    String str = Integer.toString(82);

    System.out.println(str);

  }
}
Output: 82

Parse int to String using the String.format() method

The String.format() method returns a formatted String based on the arguments.

Example

class Test {

  public static void main(String[] args) {

    int num = 501;

    String str = String.format("%d", num);

    System.out.println(str);
  }
}
Output: 501
 
Note: The %d specifies that the single variable is a decimal integer.

That’s it!

Leave a Reply

Your email address will not be published.