Different ways for Integer to String conversion in Java


Following are the different ways to convert an Integer to String in Java.

  • Using Integer.toString(int) − Convert an int to String using static toString() method of Integer class.

    String b = Integer.toString(125);
  • Using String.valueOf(int) − Convert an int to String using static valueOf() method of String class.

    String b = String.valueOf(125);
  • Using new Integer(int).toString() − Convert an int to String using toString() method of Integer object.

    String b = new Integer(125).toString();
  • Using DecimalFormat(pattern).format(int) − Convert an int to String using DecimalFormat.format() method.

    String b = new DecimalFormat("#").format(125);
  • Using StringBuilder().toString() − Convert an int to String using StringBuilder.toString() method.

    String b = new StringBuilder().append(125).toString();
  • Using StringBuffer().toString() − Convert an int to String using StringBuffer.toString() method.

    String b = new StringBuffer().append(125).toString();

Example

import java.text.DecimalFormat;

public class Tester {
   public static void main(String args[]) {
      int a = 125;

      String b = Integer.toString(a);
      System.out.println("Scenario 1: Integer.toString(int): " + b);

      b = String.valueOf(a);
      System.out.println("Scenario 2: String.valueOf(int): " + b);

      b = new Integer(a).toString();
      System.out.println("Scenario 3: new Integer(int).toString(): " + b);

      b = new DecimalFormat("#").format(a);
      System.out.println("Scenario 4: new DecimalFormat(\"#\").format(int): " + b);

      b = new StringBuilder().append(a).toString();
      System.out.println("Scenario 5: new StringBuilder().append(int).toString(): " + b);

      b = new StringBuffer().append(a).toString();
      System.out.println("Scenario 6: new StringBuffer().append(int).toString(): " + b);
   }
}

Output

Scenario 1: Integer.toString(int): 125
Scenario 2: String.valueOf(int): 125
Scenario 3: new Integer(int).toString(): 125
Scenario 4: new DecimalFormat("#").format(int): 125
Scenario 5: new StringBuilder().append(int).toString(): 125
Scenario 6: new StringBuffer().append(int).toString(): 125

Updated on: 21-Jun-2020

116 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements