February 2, 2022

How to Convert int to String in Java

This post shows several ways to convert int to String in Java.

Convert using Integer.toString() method

Wrapper class Integer has a toString() method that returns a String object representing the passed integer. Using this method you can convert int to String in Java.

public class IntToString {
  public static void main(String[] args) {
    int val = 35;
    String strVal = Integer.toString(val);
    System.out.println("Converted String value = " + strVal);
  }
}
Output
Converted String value = 35

Convert using String.valueOf() method

String.valueOf(int i)- Returns the string representation of the int argument.

public class IntToString {
  public static void main(String[] args) {
    int val = -35;
    String strVal = String.valueOf(val);
    System.out.println("Converted String value = " + strVal);
  }
}
Output
Converted String value = -35

Converting using String concatenation

You can concatenate the int value with an empty string ("") that will return the result as a String.

public class IntToString {
  public static void main(String[] args) {
    int val = 101;
    String strVal = val + "";
    System.out.println("Converted String value = " + strVal);
  }
}
Output
Converted String value = 101

Converting using append method of StringBuilder or StringBuffer class

Both StringBuilder and StringBuffer classes have append() method where you can pass int as an argument. The append() method will append the string representation of the int argument to the sequence.

public class IntToString {
  public static void main(String[] args) {
    StringBuilder sb = new StringBuilder();
    sb.append(-121);		
    System.out.println("Converted String value = " + sb.toString());
  }
}
Output
Converted String value = -121

That's all for the topic How to Convert int to String in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment