How to convert to and from a String object in Java

How to convert a String to/from int in Java?

To convert between int and String types we can take different approaches. In the examples below, we make use of the static methods provided by the Integer and String classes.

How to convert a String to an int?

String testString = "123";
int parsedInt = Integer.parseInt(testString);
System.out.println(parsedInt);

Output:

123

What if the String isn’t a valid number?

Integer.parseInt will throw a NumberFormatException in that case, for example:

String testString = "thisIsNotANumber";
try {
    Integer.parseInt(testString);
} catch (NumberFormatException ex) {
    System.out.println(ex);
}

Output:

java.lang.NumberFormatException: For input string: "thisIsNotANumber"

Converting an int to a String

There are multiple options you can choose from, here are some example:

int number = 100;
String resultString = Integer.toString(number);
System.out.println(resultString);

// other options include:
resultString = String.valueOf(number);
resultString = "" + number;
resultString = String.format("%d", number);

Output:

100

Converting Strings with different radix or base

By default Integer.parseInt converts a String assuming the number is in base 10.

However, if your String represents a binary number, you could pass the radix as the second parameter, for example:

String binaryString = "100";
int parsedInt = Integer.parseInt(binaryString, 2);
System.out.println(parsedInt);

Output:

4

You can of course, use the same approach to transform a String representing a binary, octal or hexadecimal number. You can also use other radixes if required.

Converting a number to a String in different bases

To do the opposite of the section above, we can use the Integer.toString method which also provides us with a radix parameter, for example:

int number = 16;
String resultString = Integer.toString(number, 2);
System.out.println(resultString);

Output:

10000