14. Converting int to String
As usual, in Java, we can accomplish a task in multiple ways. For instance, we can convert an int
(primitive integer) to String
via Integer.toString()
, as follows:
public String intToStringV1(int v) {
return Integer.toString(v);
}
Alternatively, you can accomplish this task via a quite common hack (the code reviewer will raise his eyebrow here), consisting of concatenating an empty string with the integer:
public String intToStringV2(int v) {
return "" + v;
}
String.valueOf()
can also be used as follows:
public String intToStringV3(int v) {
return String.valueOf(v);
}
A more esoteric approach via String.format()
is as follows:
public String intToStringV4(int v) {
return String.format("%d", v);
}
These methods also work for a boxed integer and, therefore, for an Integer
object. Since boxing and unboxing are costly operations, we strive to avoid them unless they are really necessary. However...