Skip to content

How To Convert String To Integer in Java?

Gopi Gorantala
Gopi Gorantala
2 min read

Table of Contents

In Java, you can convert a String to a Integer object using valueOf(...) method provided by Integer wrapper.

Before diving into String to Integer conversions, if you want to catch up on the basics of primitives and String to int conversions, please check the additional resources section.

String to Integer

There are two ways you could achieve this:

  1. Using Integer.valueOf
  2. Using Integer.parseInt -> Beware, this returns an int value.
public class StringToInteger {
  public static void main(String[] args) {
    String str1 = "123";
    
    // ❌ first approach (For primitives)
    int usingParseInt = Integer.parseInt(str1);
    System.out.println(usingParseInt); // 123

    // ✅ second approach (For wrapper classes)
    Integer usingValueOf = Integer.valueOf(str1);
    System.out.println(usingValueOf); // 123
  }
}

This is great, but what's happening behind the scenes? 🤔

Why the first approach is little off, and the second one seems the right one?

So you can see that the first approach is not recommended when you want to convert a string to Integer, because the Integer.parseInt returns an int primitive. This is fine when you are expecting an int type.

But we want the string to be converted into an object. Hence, we need a static method from Integer class that returns an Integer object, which is valueOf.

Beware of NumberFormatException 😬

Ok, did we do great? Is this code above enough for us to put this in production or developer-friendly codebase? Unfortunately, No ☹️.

Ask yourself, what are the chances we get a numbered string inputting our small logic? 🤔 Isn't it obvious that our snippet or algorithm should handle all cases?

Let us see why using a simple example below.

public class StringToInteger {
  public static void main(String[] args) {

    String str1 = "hello";

    Integer usingParseInt = Integer.valueOf(str1); // ❌ Throws exception
    System.out.println(usingParseInt); // this never runs
  }
}

Above code throws NumberFormatException (which sits in the java.lang package). Why can't it say a fancy StringSomeThingException? This is because the Java standard library or Java API is designed to call this a NumberFormatException.

In this case, the valueOf method throws a NumberFormatException that was intentionally designed in the Integer class. The syntax looks like:

// This is FYI, navigate to Integer class to understand more about this
public static Integer valueOf(String s) throws NumberFormatException {
  return Integer.valueOf(parseInt(s, 10));
}

Hence, the following error is thrown ☺️.

Exception in thread "main" java.lang.NumberFormatException: For input string: "hello"
	at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
	at java.base/java.lang.Integer.parseInt(Integer.java:668)
	at java.base/java.lang.Integer.valueOf(Integer.java:999)
	at dev.ggorantala.corejava.StringToInteger.main(StringToInteger.java:8)

More string conversions

public class StringToInteger {
  public static void main(String[] args) {
    System.out.println(Integer.valueOf("+100")); // 100
    System.out.println(Integer.valueOf("-100")); // -100

    /* valueOf only works for characters that are under 0-9. So each character
       in the string must adhere to this or else NumberFormatException */

    // NumberFormatException, because this contains a space character.
    System.out.println(Integer.valueOf(" 100 "));

    // NumberFormatException (decimals . or any other symbols are not allowed)
    System.out.println(Integer.valueOf("1.1"));
    System.out.println(Integer.valueOf("1-1"));

    // NumberFormatException empty string
    System.out.println(Integer.valueOf(""));

    // NumberFormatException, null cannot be a number
    System.out.println(Integer.valueOf(null));
  }
}

Try/catch to rescue ✅

Wrap your code with try-catch to handle the NumberFormatException for string inputs.

try {
  value = Integer.valueOf(str1);
} catch (java.lang.NumberFormatException nfe) {
  // the exception is always thrown
}

The refactored code, with parent Exception class looks like:

public class StringToIntegerConversion {
  public static void main(String[] args) {
    String str1 = "hello";
    int value;
    try {
      value = Integer.valueOf(str1);
      System.out.println(value); // 123
    } catch (java.lang.NumberFormatException nfe) {
      value = 0; // defaulting it to 0
      System.out.println("Exception name is " + nfe.getClass() + " " + nfe.getMessage());
    }

    System.out.println("default value = " + value);
  }
}

/* Outputs
Exception name is class java.lang.NumberFormatException For input string: "hello"
default value = 0
*/

Assigning value = 0, in the catch block is to ensure we are defaulting the forced/malformed value to 0.

Additional Resources

  1. How to convert String to int in Java?
  2. Java primitive and Non-primitive data types.
  3. What are wrapper classes in Java?
JavaJava Interview Handbook

Gopi Gorantala Twitter

Gopi is an Engineering Manager with over 14 years of extensive expertise in Java-based applications. He resides in Europe and specializes in designing and scaling high-performance applications.

Comments


Related Posts

Members Public

Spring Boot Hello World Tutorial with Lombok and H2 Database – Quick Start for Beginners

Learn how to create a Hello World Spring Boot application using Lombok for cleaner code and the H2 in-memory database for rapid development. This step-by-step guide includes annotations, project setup, REST API, H2 console access, and more to kickstart your Spring Boot journey.

Spring Boot Hello World Tutorial with Lombok and H2 Database – Quick Start for Beginners
Members Public

NoSuchBeanDefinitionException: The Most Common Spring Bean Error

Learn how to fix NoSuchBeanDefinitionException in Spring Boot with clear examples and best practices for dependency injection, package scanning, and bean registration.

NoSuchBeanDefinitionException for a missing bean in the ApplicationContext.
Members Public

BeanCurrentlyInCreationException: Circular Dependencies in Spring

Spring Boot’s DI can backfire with the dreaded BeanCurrentlyInCreationException, signaling an unresolvable circular dependency. Learn why cycles occur, how they breach SOLID principles, and three fixes—refactor to break loops, use @Lazy injection, and static @Bean factory methods—to restore startup.

Circular dependencies in Spring causing a BeanCurrentlyInCreationException