How To Convert String To int in Java?
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:
- Using
Integer.valueOf
-> Beware, this returns a wrapper object. - 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
Gopi Gorantala Newsletter
Join the newsletter to receive the latest updates in your inbox.