Low Orbit Flux Logo 2 F

Java - Convert int to string

If you’ve found your way to this page it probably means that you want to convert an int to a String in Java. This is very easy and there are multiple different ways to do this you can pick whichever method you prefer.

Quick solution: Here are four quick ways to convert an int to a string:

String s = "" + i;
String s = String.valueOf(i);
String s = Integer.toString(i);
String s = String.format("%d",i);

Keep reading for a tiny bit more info on each method and to learn how to do this with leading zeros.

String Concatenation

This first method is my favorite. You can simply concatenate an int with a string literal and assign the result to a String. We print out the result and the type of the variable.

int i = 123;
String s = "" + i;
System.out.println(s);
System.out.println(s.getClass().getName());

String.valueOf()

This method uses the valueOf() method of the String class. It will give us the String value of an int that we pass to it. This can then be returned to a String variable.

int i = 123;  
String s = String.valueOf(i);
System.out.println(s);
System.out.println(s.getClass().getName());

Integer.toString()

The Integer class itself has a toString() method that will return a String representation of whatever int you pass to it. It works pretty much as you would expect. You can assign the value to a String variable.

int i = 123;  
String s = Integer.toString(i);
System.out.println(s);
System.out.println(s.getClass().getName());

String.format()

This method also works fine but it isn’t my favorite. To me it just feels a little bit messy as you probably won’t normally get any benefit out of having to specify the format. The String class has a format() method that allows you to construct a string anyway you like. One benefit of this method is that it allows you to control things like leading zeros ( see the next section below ).

int i = 123;  
String s = String.format("%d",i);  
System.out.println(s); 
System.out.println(s.getClass().getName());

Java Convert int to String with Leading Zeros

Converting an int to a String with leading zeros is easy with Java. For this we can use the format() method of the String class. We specify “%08d” for the format. This means that the number will be padded with 0 and it will be padded up to 8 spaces.

int i = 123;
String s = String.format("%08d", i);
System.out.println(s);

Video