Convert int to String in Java

How do I convert an int to string in Java?

Given a number:

int number = 1234;

What is the best way to convert this int to string in Java so that the output is:

String stringNumber = "1234";

If you’ve been working with Java for a while, you probably know this one by heart. One of the most direct ways to convert an int to string java is using Integer.toString(int). It’s simple and does exactly what it says.

int number = 1234;
String stringNumber = Integer.toString(number);

:point_right: Integer.toString() works similarly to String.valueOf() but is specifically designed for integer conversion. If you’re dealing with integers and want clarity in your code, this is a great choice.

Yep, Integer.toString() is solid, but let me throw another option into the mix—String.valueOf(int). This is often recommended because it’s optimized for general conversions and works with all primitives.

int number = 1234;
String stringNumber = String.valueOf(number);

:point_right: String.valueOf() is a more versatile method, often preferred because it works across different data types while remaining efficient for converting an int to string java.

Now, if you’re looking for something even more concise (though not necessarily the best practice), you can use string concatenation.

int number = 1234;
String stringNumber = number + "";

:point_right: This method leverages Java’s string concatenation feature to convert an int to string java, but keep in mind that it creates an unnecessary StringBuilder object behind the scenes, making it slightly less efficient than the first two options. That said, if you’re just writing quick and dirty code, it gets the job done.