There are several ways to convert an integer to a string however in this write-up we are going to cover some most frequently used int to string conversion methods:
So, let’s begin!
Integer.toString() method in Java
Java provides a very handy method toString() which returns a string and if we use it with the Integer class then it will convert the integer value to string value.
Example
In the below-provided code snippet, we have an integer value the toString() method is utilized to convert that int value into string:
The complete code and respective output will look like this:
The output looks quite similar to the integer value, no worries! We can validate the variable’s type by using Java’s getClass().getName() method. Consider the below code snippet for a profound understanding of how to check the type of variable:
The below-given snippet shows the complete code and respective output:
Now the output verifies that the number is successfully converted into a string.
String.valueOf() method in Java
Java provides another useful method String.valueOf() that can be used to convert int to string value.
Example
Let’s consider the following example which elaborates how to use the String.valueOf() method in java:
Following will be the output of the above code snippet:
This time we verify the variable type by concatenating the values:
The complete code and its output will look like this:
In the above snippet, we have two integer values, initially, when we concatenate two integer values then we get the sum of two values.
However, when we convert an int value to a string and afterward when we add it with an integer value then we get a concatenated string:
String.format() method in Java
It takes some arguments and formats them into a String.
Example
The below-given code provides a detailed understanding of how to use String.format() method to convert an integer value to a string:
Output of the above code snippet is shown in the following figure:
Output authenticates the working of the String.format() method as it successfully converts the integer value to string value.
Conclusion
Java provides multiple methods to convert an int value to a string value such as String.format(), toString(), and valueOf() methods. To do so, an integer value will be passed to any of the above-mentioned methods, and to verify the type of variables, the getClass().getName() method can be used. This write-up elaborates various ways of converting an integer value to a string value in java.