Learning how to convert an int value to String in Java is extremely easy. However, there are multiple ways to achieve the desired result, and this is where complexity comes in. Currently, there are three ways you can convert the int value to String. Let’s go through them one by one.
String.valueOf()
The best way to convert an int value to a String is to use the String.valueOf() function. The reasoning behind this is that int is a primitive value compared to Integer, which is a wrapper object. Remember, everything in Java is an object, which makes a difference in how the conversion should be handled.
If you want to convert an int to String, you need to use String.valueof(int). You can also use the function for other data types such as float, long, etc.
So, what does it look like? Let’s see it in action below.
1 |
String morethantwenty = String.valueOf(35); |
1 |
//Output “35” |
1 2 3 |
public static String valueOf(int i) { return Integer.toString(i, 10); } |
As you can see, that it uses the .toString() method to do the conversion. This leads us to our second method of converting an int to string in Java.
Integer.toString()
The next method is toString(). It takes an integer as an argument and converts it to a string. Let’s see it in action below.
1 2 3 4 5 6 7 |
String normalconversion = Integer.toString(88); String positiveconversion = Integer.toString(+35); String addingzeroinfront = Integer.toString(05); String negativecoversion = Integer.toString(-22); |
Output
1 2 3 4 5 6 7 |
“88” “35” “5” “-22” |
String Concatenation
String concatenation also works for converting an int value to String in Java. Even though you can do it, you should not use it in production-level code. This method is only shared for the sake of knowledge and should be used with caution.
1 |
String onehundred = “” + 100; |
1 |
// output “100” |
Do you think we covered all the methods for converting int to String? Comment below and let us know.
You can also check our website for videos about Java. Below are some examples:
- Programming a Solar System (part 13) – Java
- A new method how to learn create better webpage (part 1) – Java
You can also follow some of our broadcasters who program in Java as below:
Another cool way to find out interesting things about Java is to access our project page!