To convert an int to a String in Java, you can use the Integer.toString() method. This method takes an int value as input and returns its corresponding String representation.
Here is a simple code example:
“`java
Int i = 10;
String s = Integer.toString(i);
“`
After executing this code, the variable `s` will contain the String value “10”.
The Integer.toString() method is a convenient way to convert an int to a String. It is a static method of the Integer class, which means you can call it directly without creating an instance of the Integer class.
The Integer.toString() method internally uses the String.valueOf() method to convert the int to a String. Both methods produce the same result, so you can use either of them based on your preference.
It’s important to note that there are other ways to convert an int to a String in Java. Here are a few alternatives:
1. Concatenation Operator (+):
“`java
Int i = 10;
String s = “” + i;
“`
In this approach, we concatenate an empty string with the int value using the concatenation operator (+). This forces the int value to be converted to a String.
2. String.format():
“`java
Int i = 10;
String s = String.format(“%d”, i);
“`
The String.format() method allows you to format a String using placeholders. In this case, we use the “%d” placeholder to represent the int value. By passing the int value as an argument, it gets converted to a String.
3. StringBuilder or StringBuffer:
“`java
Int i = 10;
StringBuilder sb = new StringBuilder();
Sb.append(i);
String s = sb.toString();
“`
Using a StringBuilder or StringBuffer, you can append the int value to the StringBuilder object and then convert it to a String using the toString() method.
All these approaches achieve the same result of converting an int to a String. However, the Integer.toString() method is the simplest and most commonly used method for this conversion.