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) .mapToObj(Integer::toString) .collect(Collectors.toList()); 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 bases – binary, 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:
1120
int to binary String
int x = 42; System.out.println(Integer.toBinaryString(x));
Prints:
101010
int to octal String
int x = 42; System.out.println(Integer.toOctalString(x));
Prints:
52
int to Hex String
int x = 42; System.out.println(Integer.toHexString(x));
Prints:
2a
References:
- See Java String to int for reverse conversion
- Java Basics Tutorial