Skip to content

How To Convert String To int in Java?

Gopi Gorantala
Gopi Gorantala
3 min read

Table of Contents

In Java, you can convert a String to a int primitive type using various methods provided by the Java standard library.

Before diving into String conversion to primitive types. If you want to catch up on the basics of primitives, please check the additional resources section.

To convert a Java String to int primitive type, you can use methods provided by the wrapper class Integer.

String to int

There are two ways you could achieve this:

  1. Using Integer.valueOf -> Beware, this returns a wrapper object.
  2. Using Integer.parseInt
public class StringToIntConversion {
  public static void main(String[] args) {
    String str1 = "123";

    // ❌ first approach (For wrapper classes)
    int usingValueOf = Integer.valueOf(str1);
    System.out.println(usingValueOf); // 123

    // ✅ second approach (For primitives)
    int usingParseInt = Integer.parseInt(str1);
    System.out.println(usingParseInt); // 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 primitives because the Integer.valueOf returns an Integer object. This is fine when you are expecting a wrapper class.

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

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 use see why using a simple example below.

public class StringToIntConversion {
  public static void main(String[] args) {
    String str1 = "hello";

    int usingParseInt = Integer.parseInt(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. That the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format. 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.parseInt(Integer.java:786)
	at dev.ggorantala.corejava.StringToPrimitives.main(StringToPrimitives.java:7)

Process finished with exit code 1

More string conversions

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

    /* parseInt 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.parseInt(" 100 "));

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

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

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

Try/catch to rescue ✅

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

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

The refactored code, with the parent Exception class looks like this:

public class StringToIntConversion {
  public static void main(String[] args) {
    String str1 = "hello";
    int value;
    try {
      value = Integer.parseInt(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.

Using Google library

We are using Google library with Java 8's Optional, which makes them both powerful and concise ways to convert string into an int.

import java.util.Optional;

public class StringToIntConversion {
  public static void main(String[] args) {
    String str1 = "hello";
    int value = Optional.ofNullable(str1)
      .map(com.google.common.primitives.Ints::tryParse)
      .orElse(0);

    System.out.println(value); // 0
  }
}

Additional Resources

  1. How to convert String to Integer 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 leader with 12+ of experience in full-stack development—a specialist in Java technology stack. He worked for multiple startups, the European govt, and FAANG in India and Europe.

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.