4 methods to transform int to String in Java – Instance
Following is the listing of 4 strategies you should utilize to transform an int worth to String object in Java :
1) String.concat() or + operator
2) String.valueOf()
3) Integer.toString()
4) String.format()
Answer 1 – String concatenation
Best technique to convert an int primitive worth to String is by simply concatenating int to an empty String e.g.
String fromInt = "" + worth;
Internally this code will get transformed into StringBuilder e.g. new StringBuilder().append(“”).append(vlaue).toString(); so it does unnecessarily allocate a bigger buffer (default dimension of StringBuilder is 16) then required however its very straightforward on the face, and good for testing, demo objective.
Btw, you can too use concat() methodology as an alternative of + operator for doing String concatenation in Java.
Answer 2 – String.valueOf()
In Java, the usual technique to convert something to String is through the use of String.valueOf() methodology. So you can too convert an int to String utilizing this methodology as proven under :
int worth = 20;
String str = String.valueOf(worth);
The String returned by this methodology is strictly identical because the one returned by Integer.toString() methodology.
Answer 3 – Integer.toString()
This isn’t the dirct however one other technique to convert int to String in Java. You should not be utilizing it until you’re changing an Integer to String somewhat than an int to String, however its value figuring out. You’ll be able to first use autoboxing to wrap an int to Integer after which name its toString() methodology as proven under :
Integer i = 10;
String s = i.toString();
The String returned is strictly identical as that returned by Integer.valueOf() methodology.
Answer 4 – String.format()
This can be a somewhat un-common technique to convert an int to String, works solely after Java 1.5 as a result of format() methodology was added on that launch. Right here is how you should utilize format() methodology to transform an int to String in Java :
String amount = String.format("%d", 10000);
And, here’s a abstract of all of the 4 methods to transform an int to String in Java: