How to Convert Int to String in Java
In Java, converting an integer (int) to a string (String) can be achieved using one of two methods:
int i = 5; String strI = Integer.toString(i);
These methods are the preferred and conventional ways to perform int-to-string conversions.
Avoid Using Concatenation
The code you provided, which uses concatenation (" "), is an unconventional approach:
int i = 5; String strI = "" + i;
While concatenation will work, it is discouraged as it suggests a lack of familiarity with the proper methods for converting ints to strings.
Compiler Behavior
The compiler does not optimize out the empty string in the concatenation approach. Instead, it initializes a StringBuilder, appends the empty string, then appends the int and extracts the final string. This results in slightly lower efficiency compared to the Integer.toString() and String.valueOf() methods.
Proposed Change
There is ongoing work to address this inefficiency and potentially optimize the concatenation approach in future versions of Java (e.g., JDK 9). However, currently, the recommended practice is to use Integer.toString() or String.valueOf().
The above is the detailed content of What's the Best Way to Convert an Integer to a String in Java?. For more information, please follow other related articles on the PHP Chinese website!