Why does the Integer.toString()
method is implemented using String.valueOf(int i)
instead of using directly static method Integer.toString(int i)
which is called back by String.valueOf(int i)
?
Update: I am working with a Sun (Oracle now) jdk 1.6.0_12
toString(int a) is an inbuilt method in Java which is used to return a String object, representing the specified integer in the parameter. Parameters: The method accepts one parameter a of integer type and refers to the integer needed to be converted to string.
Integer toString() in Java Integer. toString(int i) method returns a String object representing the specified integer. Here, i is the integer to be converted.
toString() is supposed to return a string containing a "description" of the object. It's not supposed to print anything.
You will clearly see that String. valueOf(int) is simply calling Integer. toString(int) for you. Therefore, there is absolutely zero difference, in that they both create a char buffer, walk through the digits in the number, then copy that into a new String and return it (therefore each are creating one String object).
The reason is probably historical. The Java 1.0 release was made in a hurry to try to meet (what was perceived to be) a closing window of opportunity. Many mistakes were made in the API design. But by the time of Java 1.1, designers realized that fixing mistakes in the API could break existing programs, and alienate developers and users. So they opted for leaving mistakes (especially minor inconsistencies) unfixed.
This is just one of those minor inconsistencies. It makes no difference in practice since the JIT compiler will inline the calls anyway.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With