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 a software engineer with over 14 years of experience. He specializes in Java-based technology stack and has worked for various startups, the European government, and technology giants.

Comments


Related Posts

Members Public

Differences Between JDK, JRE, and JVM?

Short answer JDK, JRE, and JVM are essential components of the Java platform, each serving a distinct purpose. Here are the key differences between them: 1. JDK (Java Development Kit): The JDK is used by developers to write, compile, and debug Java code. 2. JRE (Java Runtime Environment): End-users use

Members Public

Difference Between String and char[] in Java

Short answer Strings String is an object with many helpful methods. String class in Java's standard library is designed to handle text as a sequence of characters. A string of characters (string object) is non-modifiable or immutable in Java. Once you've created it, you cannot modify

Members Public

What is an Object class in Java?

Short answer Object class is the super class of every class you can create. In Java, a class extends another class using the keyword extends. If you don't have any other class to extend, that's fine. The compiler will make your class extend the Object class.