To convert an int value into a String, we can use either String.valueOf() or Integer.toString() method. Internally, the former calls the latter, so Integer.toString() should be preferred.
1. Using Integer.toString()
The Integer.toString(int) returns a string representing the specified int passed as method argument. By default, the argument is converted to signed decimal (radix 10) in string format.
String toString(int i);
For example, we can pass any positive or negative value and get its value in string.
Assertions.assertEquals("0", Integer.toString(0));
Assertions.assertEquals("40", Integer.toString(40));
Assertions.assertEquals("-40", Integer.toString(-40));
1.1. No Exception Thrown
Be careful to not exceed the maximum or minimum value of the int type that is 2147483647 and -2147483648. We will get unexpected results in case we cross the upper or lower bounds.
Assertions.assertEquals("2147483647", Integer.toString(Integer.MAX_VALUE));
Assertions.assertEquals("-2147483648", Integer.toString(Integer.MAX_VALUE + 1));
Assertions.assertEquals("-2147483648", Integer.toString(Integer.MIN_VALUE));
Assertions.assertEquals("2147483647", Integer.toString(Integer.MIN_VALUE - 1));
1.2. Binary, Octal and Hex Strings
Note that we can use several other inbuilt methods if we want to get the String value in other base values. The default base is 10.
- Integer.toBinaryString(): returns string representation in base 2.
- Integer.toOctalString(): returns in base 8.
- Integer.toHexString(): returns in base 16.
Assertions.assertEquals("101000", Integer.toBinaryString(40));
Assertions.assertEquals("50", Integer.toOctalString(40));
Assertions.assertEquals("28", Integer.toHexString(40));
2. Using String.valueOf()
The String.valueOf(int i) returns the string representation of the int argument. It internally invokes the Integer.toString() so the the representations are always exactly the same.
String valueOf(int i);
Lets test out the int values again as in previous section.
Assertions.assertEquals("0", String.valueOf(0));
Assertions.assertEquals("40", String.valueOf(40));
Assertions.assertEquals("-40", String.valueOf(-40));
Assertions.assertEquals("2147483647", String.valueOf(Integer.MAX_VALUE));
Assertions.assertEquals("-2147483648", String.valueOf(Integer.MAX_VALUE + 1));
Assertions.assertEquals("-2147483648", String.valueOf(Integer.MIN_VALUE));
Assertions.assertEquals("2147483647", String.valueOf(Integer.MIN_VALUE - 1));
3. Conclusion
In Java, converting an int value to a String is not a difficult task but knowing which method may save us few CPU cycles is worth knowing it. In this case, we should always prefer the Integer.toString() to int to String conversions.
Happy Learning !!