How To Convert String To Integer in Java?
Table of Contents
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
There are two ways you could achieve this:
- Using
Integer.valueOf
- Using
Integer.parseInt
-> Beware, this returns an int value.
public class StringToInteger {
public static void main(String[] args) {
String str1 = "123";
// ❌ first approach (For primitives)
int usingParseInt = Integer.parseInt(str1);
System.out.println(usingParseInt); // 123
// ✅ second approach (For wrapper classes)
Integer usingValueOf = Integer.valueOf(str1);
System.out.println(usingValueOf); // 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 Integer
, because the Integer.parseInt
returns an int
primitive. This is fine when you are expecting an int
type.
But we want the string to be converted into an object. Hence, we need a static method from Integer
class that returns an Integer
object, which is valueOf
.
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 us see why using a simple example below.
public class StringToInteger {
public static void main(String[] args) {
String str1 = "hello";
Integer usingParseInt = Integer.valueOf(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
.
In this case, the valueOf
method throws a NumberFormatException
that was intentionally designed in the Integer
class. The syntax looks like:
// This is FYI, navigate to Integer class to understand more about this
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
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.valueOf(Integer.java:999)
at dev.ggorantala.corejava.StringToInteger.main(StringToInteger.java:8)
More string conversions
public class StringToInteger {
public static void main(String[] args) {
System.out.println(Integer.valueOf("+100")); // 100
System.out.println(Integer.valueOf("-100")); // -100
/* valueOf 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.valueOf(" 100 "));
// NumberFormatException (decimals . or any other symbols are not allowed)
System.out.println(Integer.valueOf("1.1"));
System.out.println(Integer.valueOf("1-1"));
// NumberFormatException empty string
System.out.println(Integer.valueOf(""));
// NumberFormatException, null cannot be a number
System.out.println(Integer.valueOf(null));
}
}
Try/catch to rescue ✅
Wrap your code with try-catch
to handle the NumberFormatException
for string inputs.
try {
value = Integer.valueOf(str1);
} catch (java.lang.NumberFormatException nfe) {
// the exception is always thrown
}
The refactored code, with parent Exception
class looks like:
public class StringToIntegerConversion {
public static void main(String[] args) {
String str1 = "hello";
int value;
try {
value = Integer.valueOf(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
.
Additional Resources
Gopi Gorantala Newsletter
Join the newsletter to receive the latest updates in your inbox.