Java int to String - Integer.toString(i) vs new Integer(i).toString()
In Java, there are several ways to convert an int
value to a String
:
- Using the
Integer.toString()
method:
int i = 42;
String s = Integer.toString(i);
- Using the
String.valueOf()
method:
int i = 42;
String s = String.valueOf(i);
- Using the
new Integer(i).toString()
method:
int i = 42;
String s = new Integer(i).toString();
- Using string concatenation:
int i = 42;
String s = "" + i;
- Using the
String.format()
method:
int i = 42;
String s = String.format("%d", i);
All of these methods will convert an int
value to a String
representation of that value. The choice of which method to use will depend on the specific requirements of your program.
Option 1 and 2 are the most common and recommended ways to convert an int
to a String
. Option 3 creates a new Integer
object to hold the int
value, which can be less efficient than the other options. Option 4 and 5 are also commonly used, but they may be less efficient or less readable than the other options, depending on the context.