Convert String to int in Java

Published by user on

In this article, we will look at the ways to convert String to int in Java using Integer.parseInt() and Integer.valueOf() methods.

One of the main reason for conversion is that we can easily perform mathematical operations on the int data type.

Convert String to int using Integer.parseInt()

If you want primitive int, then you can use Integer.parseInt(String s).

For a successful conversion, all the character in String has to be decimal digit except the first character which can be a sign.

public class ParseIntExample {

	public static void main(String[] args) {

		String str = "200";
		int intValue = Integer.parseInt(str);
		System.out.println("int value is : " + intValue);

		String signedStr = "-300";
		int signedIntValue = Integer.parseInt(signedStr);
		System.out.println("signed int value is : " + signedIntValue);

	}
}

Output:

int value is : 200
signed int value is : -300

String to int in java

Convert using Integer.valueOf()

In case you want to convert String to java.lang.Integer then you can use Integer.valueOf(String s) method. It is a static method and can operate on both unsigned and signed values.

public class ValueOfExample {

	public static void main(String[] args) {

		String input = "600";
		Integer output = Integer.valueOf(input);
		System.out.println("Integer value is : " + output);

		String signedInput = "-900";
		Integer signedOutput = Integer.parseInt(signedInput);
		System.out.println("Signed Integer value is : " + signedOutput);

	}
}

Output:

Integer value is : 600
Signed Integer value is : -900

If the String doesn’t contain a parsable value, then both of the above methods throw NumberFormatException.

When we say parsable, it means all the character in the string must be decimal digits and the first character can be either + or – sign. No other signs are allowed.

Valid Example:

Below examples are parsable.

  • “-100”
  • “+500”
  • “100”

Non-parsable example:

Below examples are not parsable.

  1. “*500”
  2. “50f9”

First one contains ‘*’ so it is invalid, whereas the second one contains ‘f’ so it is not parsable.

Summary:

  1. We learnt about Integer.parseInt() and Integer.valueOf() method.
  2. We also saw what NumberFormatException is and when it is thrown.

That’s it for this tutorial developers. If you like our article, please share it.

References

NumberFormatException
Integer class

Categories: Java