Skip to content

How To Convert String To int in Java?

ggorantala
ggorantala
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?
Java

ggorantala Twitter

Gopi has a decade of experience with a deep understanding of Java, Microservices, and React. He worked in India & Europe for startups, the EU government, and tech giants.

Comments


Related Posts

Members Public

What Are Wrapper Classes In Java?

This is the most asked interview question! Why do we use wrapper classes to store data for a model class instead of primitives? What are wrapper classes? Primitive wrappers, also known as wrapper classes, are a set of classes in Java that provide an object representation for the primitive data

Members Public

How To Convert String To Integer in Java?

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

Members Public

What Are Java Features?

Java is a widely used, high-level programming language known for its versatility and platform independence. Its robust features suit various applications, from web development to enterprise-level software. Key features The key features collectively contribute to Java's popularity and wide adoption across a diverse range of industries and application domains. Simple