Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Java int to String

In Java int to String conversion can be done in a different ways and converted String can be in different formats. In this post we’ll show on examples how to convert them.

Concatenate String with int

The simplest method is to use automatic conversion of int to String using + operator:

int x = 42;
String s = "" + x;
System.out.printf("Number: '%s'%n", s);

The above code produces the following output:

Number: '42'

int to String using Integer.toString(int)

Another way to convert int to String is using Integer.toString(int) method:

int x = 42;
String s = Integer.toString(x);
System.out.printf("Number: '%s'%n", s);

The result is as expected:

Number: '42'

Java 8 map int to String

The Integer.toString(int) method seems unneeded, but it turns out that it’s very handy when working with Java 8 Streams. In the following example we’ve got a Stream of int numbers and want to convert them to Strings. Having Integer.toString(int) we can pass it as a method reference to the Stream.mapToObj(IntFunction) to do int to String conversion:

List<String> numbers = IntStream.of(1, 2, 3)
System.out.printf("Numbers: '%s'%n", numbers);

Stream of int converted to List of Strings:

Numbers: '[1, 2, 3]'

Integer to String conversion

If you have Integer objects you can convert them using their toString() method:

Integer x = 42;
String s = x.toString();
System.out.printf("Number: '%s'%n", s);

The code prints the same result:

Number: '42'

int to String in other base

Integer class has a number of methods to help in conversion of Integer to String in different basesbinary, octal, hexadecimal. These methods are sometimes helpful in algorithmic exercises, when there’s a need to operate on binary Strings.

int to n-based String

int x = 42;
System.out.println(Integer.toString(x, 3));

The number as 3-based String:


int to binary String

int x = 42;



int to octal String

int x = 42;



int to Hex String

int x = 42;




Share with the World!