Java String to Int

A common requirement while programming in Java is to convert String to int. UI inputs in Web-based HTML, JSP, or Thymeleaf templates are transferred to backend Java applications as strings. It is the application developer’s responsibility to perform any String to int conversions to fulfil business logic, such as calculating discounts, storing age, and so on.

In this post, I’ll discuss how to convert String in Java to int.

The Integer.parseInt Method

The Integer.parseInt() method takes as input a String and returns an int value.

The code to use this method is this.

Here is test code in JUnit.

The output on running the test in InteliJ is this.

Test Output converting string to int in Java

The Integer class also provides an overloaded parseInt() method that additionally accepts the radix (base) to be used while parsing.

Here is the code to use the overloaded method..

Here is the test code.

The output on running the test in InteliJ is this.
Java string to int using radix (base)

Handling Parsing Exception

The parseInt() method throws a NumberFormatException if the String does not contain a parsable int.

Here is sample code to handle the NumberFormatException  gracefully.

This code returns a default int value whenever a NumberFormatException is thrown by the parseInt() method.

Here is the Junit test code.

The test output is this.
Java string to int output

The Integer.valueOf Method

The Integer class also comes with the static valueOf() method to convert String to int. The valueOf() method interprets the String exactly as if it were given to parseInt(). In fact, the valueOf() method internally uses the parseInt() method.

However, valueOf() returns a new Integer object whereas parseInt() returns a primitive int.

The code to parse String using the valueOf() method is this.

Here is the Junit test code.

The test output is this.

Java string to integer output

Note: Similar to parseInt(), the valueOf() method also have an overloaded version that accepts an additional radix value.

Conclusion

Considering Java is a strongly typed language and often interfaces with systems that do not have the type system of Java, converting from a string value to an int value in Java is very common task. As you can see Java provides a number of different ways to convert a string value to an integer value.

 

Share

Leave a Reply