You cannot cast from String to Integer. However, if you are trying to convert string into integer and if you have to provide an implementation for handling null Strings, take a look at this code snippet:

String str = "...";
// suppose str becomes null after some operation(s).
int number = 0;
try
{
    if(str != null)
      number = Integer.parseInt(str);
}
catch (NumberFormatException e)
{
    number = 0;
}
Answer from Juvanis on Stack Overflow
Top answer
1 of 4
11

null is not a valid representation of integer number. Integer.parseInt() requires that the string be parsed is a vaild representation of integer number.

Integer.parseInt()

  public static int parseInt(String s, int radix)
440                 throws NumberFormatException
441     {
442         if (s == null) {
443             throw new NumberFormatException("null");
444         }

Integer.valueOf(str)] // which inviokes Integer.parseInt(Str) to return an Integer instance.

  public static Integer valueOf(String s) throws NumberFormatException
569     {
570         return new Integer(parseInt(s, 10));
571     }
2 of 4
9

The folks at Sun who implemented Integer (a long time ago :) ) probably were not thinking of databases when they wrote that method. Except when dealing with database data, or rare cases where you are trying to explicitly represent "unknown" with null, null is usually a sign of something gone terribly wrong. In general, it's a good idea to raise an exception as soon as there is a problem. (a Fail fast design)

If you have ever spent time hunting down a segmentation fault in C that is due to a string value longer than the memory you supplied for it (which then overwrote some program code or other data) you will have a very good appreciation of how bad it is to not fail when something has gone wrong.

Since the time of Java 1.0, interaction with databases in java has become extremely common so you might be right to suggest that there should be a method to handle this. Integer is a final class so if you build your own Integer like class you will loose autoboxing, so this probably does require a change to the language by oracle.

Basically, what you observed is the way it is for now, and someone will have to pay you to code around it :)

Discussions

java - Why do Double.parseDouble(null) and Integer.parseInt(null) throw different exceptions? - Stack Overflow
Integer.parseInt(null); // throws java.lang.NumberFormatException: null ... Checking the source code of the respective methods, it seems like just an inconsistency. parseDouble does not do a null check, and just throws an NPE when it is encountered, but in parseInt, then input string is checked ... More on stackoverflow.com
🌐 stackoverflow.com
I can not get why i still get the problem with can not parse null string when i have an if excluding null values
null players are excluded but what about players with null score? That is what you are actually parsing! More on reddit.com
🌐 r/learnjava
5
0
February 1, 2023
java - Proper way to avoid parseInt throwing a NumberFormatException for input string: "" - Stack Overflow
Check for null, and/or... ... Sign up to request clarification or add additional context in comments. ... Save this answer. ... Show activity on this post. Well, you could use the conditional operator instead: Copyreturn StringUtils.isNotBlank(myString) ? Integer.parseInt(myString) : 0; More on stackoverflow.com
🌐 stackoverflow.com
Integer.parseInt and nextInt()
There is a big difference between the two, so big that they actually have nothing to do with each other. Integer.parseInt works on a String. That String can come from anywhere. It is not limited to the Scanner class. Scanner.nextInt is a method of the Scanner class that waits for an int on the input stream of the Scanner. If it sees a valid integer, it takes it and returns it as an int. If it sees something different to an integer, it throws an exception. The caveat with nextInt or nextDouble is that a possible line break (i.e. Enter) is left in the input buffer. In fact, the nextInt method internally uses Integer.parseInt to produce the int value. Which one do real programmers in the real world use most? They use both, depending on the situation. As I've said above, the two methods are actually not related to each other. More on reddit.com
🌐 r/learnjava
10
5
April 5, 2015
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
OpenJDK
bugs.openjdk.org › browse › JDK-8318646
Integer#parseInt("") throws empty NumberFormatException ...
We hit this bug with Lucene tests. When you parse an empty string with Integer#parseInt(""), it thros an NumberFormatException with an empty message.
🌐
Coderanch
coderanch.com › t › 773925 › java › resolve-error-Message-parse-null
How to resolve the error: Message Cannot parse null string (Servlets forum at Coderanch)
June 30, 2023 - If the servlet's request doesn't contain the "num1" parameter then req.getParameter() returns null. This happens when the client doesn't type anything in that input field of the form. So instead of just trying to parse null as an integer, you need to decide what you want to do with null values and write code to act accordingly.
🌐
Talentify
talentify.com › home › 4 different ways to use integer.parseint in java
4 different ways to use Integer.parseInt in Java | Talentify
June 3, 2021 - If the passed string is null or not a valid integer, this method will return the defaultValue. We can add some simple sanitization of the String to increase the probability of successful conversion using the String.trim method.
🌐
Global Tech Council
globaltechcouncil.org › home › blogs › what is parseint in java?
What is parseInt in Java? - Global Tech Council
June 9, 2026 - Here’s how to handle two common problems: This error happens when Java tries to turn a string into an integer but finds something it doesn’t expect. This could be because: The string is empty or null.
Find elsewhere
🌐
TutorialKart
tutorialkart.com › java › java-string-to-int
Convert String to Int in Java
May 4, 2023 - Not a valid int value."); } catch (NullPointerException e) { System.out.println("Check the string. String is null."); } System.out.print(n); } } Just like Integer.parseInt(), the function Integer.valueOf() also throws NullPointerException if the string argument is null, or a NumberFormatException if the string does not parse to a valid int value.
🌐
LabEx
labex.io › tutorials › java-how-to-parse-integer-from-string-safely-422167
How to parse integer from string safely | LabEx
public class RobustParsingDemo { public static Integer robustParse(String input) { if (input == null || input.trim().isEmpty()) { return null; } try { int parsedValue = Integer.parseInt(input.trim()); // Additional custom validations if (parsedValue < 0 || parsedValue > 1000) { System.out.println("Value out of acceptable range"); return null; } return parsedValue; } catch (NumberFormatException e) { System.out.println("Invalid number format"); return null; } } public static void main(String[] args) { String[] testInputs = {"123", " 456 ", "abc", "1500", null}; for (String input : testInputs) { Integer result = robustParse(input); System.out.println("Input: " + input + ", Result: " + result); } } }
🌐
Blogger
javahungry.blogspot.com › 2020 › 05 › java.lang.numberformatexception-input-string.html
[Solved] java.lang.NumberFormatException: For input string | Java Hungry
class JavaHungry { public static void main(String args[]) { String s = null; int i = Integer.parseInt(s); System.out.println(i); } } Output: Exception in thread "main" java.lang.NumberFormatException: For input string: "null" In Java, Empty String can’t be converted into a primitive data type.
🌐
Blogger
javarevisited.blogspot.com › 2016 › 08 › javalangnumberformatexception-for-input-string-null-java.html
How to fix java.lang.numberformatexception for input string null - Cause and Solution
The error "Exception in thread "main" java.lang.NumberFormatException: For input string: "null" is specifically saying that the String you receive for parsing is not numeric and it's true, "null" is not numeric.
🌐
Qlik Community
community.qlik.com › t5 › Design-and-Development › resolved-Tmap-String-to-Int-And-return-null-if-null › td-p › 2198554
Solved: [resolved] Tmap - String to Int - And return null ... - Qlik Community - 2198554
November 16, 2024 - Hi do it like this (row1.value1==null || row1.value1=="" )?null:Integer.parseInt(row1.value1) or you can use (row1.value1.length >0 )?null:Integer.parseInt(row1.value1) Regards Vijay.M ... Ditto - same here! ... Yes, you are right. let us know if you don't get the expected result. Best regards Shong ... I get this error: Exception in component tMap_1 java.lang.NumberFormatException: For input string: "" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at talenddemosjava.myJob_0_1.myJob.tFileInputDelimited_1Process(myJob.java:1171) at talenddemosjava.myJob_0_1.myJob.runJobInTOS(myJob.java:1682) at talenddemosjava.myJob_0_1.myJob.main(myJob.java:1556)
🌐
Artful
journal.artful.dev › what-you-risk-when-using-number-to-parse-an-integer-from-a-string-in-typescript
What you risk when using Number() to parse an integer from a string in TypeScript
May 15, 2023 - If we provide a null or undefined input, parseInt will return an NaN (as expected, I hope). I’ve listed some sample inputs and outputs of both the functions here. Some of the cases that might be baffling are actually reasonable: Some important ...
🌐
DEV Community
dev.to › darkmavis1980 › you-should-stop-using-parseint-nbf
You should stop using `parseInt()` - DEV Community
October 15, 2021 - Unfortunately all oneliners in Javascript are broken. Nothing works. Neither parseInt nor Number nor any other implicit or explicit attempt to convert the value. You always have to use a combination of different functions plus some manual checking for special cases like empty string, null, or undefined...
🌐
Rollbar
rollbar.com › home › how to handle the numberformatexception in java
How to Handle the NumberFormatException in Java | Rollbar
June 29, 2025 - Simply put, if you attempt to parse "hello" as an integer or "12.5" as an integer, Java throws a NumberFormatException because these strings can't be converted to the expected numeric format.
🌐
Reddit
reddit.com › r/learnjava › i can not get why i still get the problem with can not parse null string when i have an if excluding null values
r/learnjava on Reddit: I can not get why i still get the problem with can not parse null string when i have an if excluding null values
February 1, 2023 -

public void sortHighscore(){

for(int i = 0; i < players.length; i++) {
int min_index = i;
for (int j = i + 1; j < players.length; j++) {
if(players[j] != null && players[i] != null) {
if (Integer.parseInt(players[j].getScore()) < Integer.parseInt(players[i].getScore())) {
min_index = j;
}
}
}
Player temp = players[min_index];
players[min_index] = players[i];
players[i] = temp;
}
}

Please if someone can see what the problem may be

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › parseInt
parseInt() - JavaScript - MDN Web Docs
The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN.