> ## Content Index
> Fetch the complete content index at: https://www.ggorantala.dev/llms.txt
> Use this file to discover other available public pages before exploring further.

# How To Convert String To int in Java?
- URL: https://www.ggorantala.dev/how-to-convert-string-to-int-in-java/
- Published: 2023-09-12T15:09:00.000Z
- Updated: 2023-09-20T19:14:27.000Z
- Author: Gopi Gorantala
- Tags: Java, Java Interview Handbook

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`

```java
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.

```java
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 ☺️.

```java
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

```java
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. 

```java
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:

```java
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. 

```java
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?](https://www.ggorantala.dev/how-to-convert-string-to-integer-in-java/)
2. [Java primitive and Non-primitive data types](https://www.ggorantala.dev/java-primitive-and-non-primitive-data-types/).
3. [What are wrapper classes in Java?](https://www.ggorantala.dev/what-are-wrapper-classes-in-java/)