You could return an Integer instead of an int, returning null on parse failure.

It's a shame Java doesn't provide a way of doing this without there being an exception thrown internally though - you can hide the exception (by catching it and returning null), but it could still be a performance issue if you're parsing hundreds of thousands of bits of user-provided data.

EDIT: Code for such a method:

public static Integer tryParse(String text) {
  try {
    return Integer.parseInt(text);
  } catch (NumberFormatException e) {
    return null;
  }
}

Note that I'm not sure off the top of my head what this will do if text is null. You should consider that - if it represents a bug (i.e. your code may well pass an invalid value, but should never pass null) then throwing an exception is appropriate; if it doesn't represent a bug then you should probably just return null as you would for any other invalid value.

Originally this answer used the new Integer(String) constructor; it now uses Integer.parseInt and a boxing operation; in this way small values will end up being boxed to cached Integer objects, making it more efficient in those situations.

Answer from Jon Skeet on Stack Overflow
Top answer
1 of 16
161

You could return an Integer instead of an int, returning null on parse failure.

It's a shame Java doesn't provide a way of doing this without there being an exception thrown internally though - you can hide the exception (by catching it and returning null), but it could still be a performance issue if you're parsing hundreds of thousands of bits of user-provided data.

EDIT: Code for such a method:

public static Integer tryParse(String text) {
  try {
    return Integer.parseInt(text);
  } catch (NumberFormatException e) {
    return null;
  }
}

Note that I'm not sure off the top of my head what this will do if text is null. You should consider that - if it represents a bug (i.e. your code may well pass an invalid value, but should never pass null) then throwing an exception is appropriate; if it doesn't represent a bug then you should probably just return null as you would for any other invalid value.

Originally this answer used the new Integer(String) constructor; it now uses Integer.parseInt and a boxing operation; in this way small values will end up being boxed to cached Integer objects, making it more efficient in those situations.

2 of 16
41

What behaviour do you expect when it's not a number?

If, for example, you often have a default value to use when the input is not a number, then a method such as this could be useful:

public static int parseWithDefault(String number, int defaultVal) {
  try {
    return Integer.parseInt(number);
  } catch (NumberFormatException e) {
    return defaultVal;
  }
}

Similar methods can be written for different default behaviour when the input can't be parsed.

🌐
Scaler
scaler.com › home › topics › parseint() in java
parseInt() in Java - Scaler Topics
May 8, 2024 - It is used in java for converting ... throws three exceptions: NullPointerException, IndexOutOfBoundsException, NumberFormatException when the input arguments are not according to the conventions....
🌐
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.
🌐
Quora
quora.com › Why-does-parseInt-give-a-number-format-exception
Why does parseInt give a number format exception? - Quora
Answer (1 of 6): Well, exception name says it all. You don't really have an integer number in that string. It might be empty string as Andrew Blowe, it might have some invalid characters. The only valid characters for the parsing are digits (0123456789) and sign characters (+-). The latter can be...
🌐
vteams
vteams.com › blog › use-of-parseint-java-programming
Learn the Basics & Ins-And-Outs of PARSEint Java Programming
February 23, 2024 - If you specify an invalid radix, PARSEInt will throw an exception. If the string does not contain a valid integer, PARSEInt will return 0. To PARSE something in computer science means separating a string into small components which can be easily ...
Find elsewhere
🌐
Dot Net Perls
dotnetperls.com › parseint-java
Java - parseInt: Convert String to Int - Dot Net Perls
A Java String cannot be used like an int—it cannot be incremented. It contains chars, textual data. With parseInt we convert a string to an int. ParseInt can lead to complex problems—it throws a NumberFormatException on invalid data. Many exceptions will lead to slower program performance.
🌐
Coderanch
coderanch.com › t › 393405 › java › Integer-parseInt-NumberFormatException
Integer.parseInt : NumberFormatException (Beginning Java forum at Coderanch)
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums · this forum made possible by our volunteer staff, including ... ... Please would someone tell me why the following Integer.parseInt statement throws a NumberFormatException: String string = properties.getProperty("flag"); int i = Integer.parseInt(string); The value of string is "0" ("zero").
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › Integer.html
Integer (Java Platform SE 8 )
October 20, 2025 - Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') or plus sign '+' ('\u002B') provided that the string is longer than length 1. The value represented by the string is not a value of type int.
🌐
OpenJDK
bugs.openjdk.org › browse › JDK-8318646
Loading...
JDK-8317515 it was correctly using NumberFormatException#forInputString("",..) which creates a correct message like: java.lang.NumberFormatException: For input string: "" Reproduce: $ ./jdk-17.0.2/bin/jshell | Welcome to JShell -- Version 17.0.2 | For an introduction type: /help intro jshell> Integer.parseInt(""); | Exception java.lang.NumberFormatException: For input string: "" | at NumberFormatException.forInputString (NumberFormatException.java:67) | at Integer.parseInt (Integer.java:678) | at Integer.parseInt (Integer.java:786) | at (#1:1) $ ./jdk-22/bin/jshell | Willkommen bei JShell - Ve
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.lang.integer.parseint
Integer.ParseInt Method (Java.Lang) | Microsoft Learn
<li>The radix is either smaller than java.lang.Character#MIN_RADIX or larger than java.lang.Character#MAX_RADIX. <li>Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u005Cu002D') or plus sign '+' ('\u005Cu002B') provided that the string is longer than length 1. <li>The value represented by the string is not a value of type int. </ul> ... parseInt("0", 10) returns 0 parseInt("473", 10) returns 473 parseInt("+42", 10) returns 42 parseInt("-0", 10) returns 0 parseInt("-FF", 16) returns -255 parseInt("1100110", 2) returns 102 parseInt("2147483647", 10) returns 2147483647 parseInt("-2147483648", 10) returns -2147483648 parseInt("2147483648", 10) throws a NumberFormatException parseInt("99", 8) throws a NumberFormatException parseInt("Kona", 10) throws a NumberFormatException parseInt("Kona", 27) returns 411787
🌐
Tutorialspoint
tutorialspoint.com › home › java/lang › java integer parseint method
Java Integer parseInt Method
September 1, 2008 - The following example shows the usage of Integer parseInt() method to get a Integer object from a string containing a octal number. We've created a String variable and assign it a string containing an octal number. Then using parseInt method, we're trying to obtain an Integer object and exception will be raised.
🌐
Reddit
reddit.com › r/javahelp › integer.parseint() is bugging out on me
r/javahelp on Reddit: Integer.parseInt() is bugging out on me
January 8, 2018 -

Hey guys so I am trying to parse integer from a string in the following function and I get the following error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "9876543210"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:583)
at java.lang.Integer.parseInt(Integer.java:615)
at Solution.plusOne(Solution.java:129)
at Solution.main(Solution.java:149)

Here is my following code:

    public static int[] plusOne(int[] digits)
{
    StringBuilder str = new StringBuilder();
    for(int c:digits)
    {
        str.append(c);
    }
    String num = str.toString().trim();
    System.out.println(num);
    int sum = Integer.valueOf(num)+1; //I have used Integer.parseInt(num) also
    String temp = ""+sum;
    int[] total = new int[temp.length()];
    for(int i=0;i<temp.length();i++)
    {
        total[i]=Character.getNumericValue(temp.charAt(i));
    }

    return total;
}






public static void main(String[] args)
{

    int[] arr = {9,8,7,6,5,4,3,2,1,0};
   System.out.println(plusOne(arr));

}

I am curious where I am going wrong here since I am pretty sure my string sum does not have any spaces or characters. Any help would be appreciated!

🌐
H2K Infosys
h2kinfosys.com › blog › introduction to parseint in java
Introduction to ParseInt in Java
September 24, 2024 - It’s crucial to keep in mind that a NumberFormatException will be raised if the text supplied to parseInt is not a valid integer representation. You can examine the input before calling parseInt, or you can use a try-catch block to handle ...
🌐
Java Programming
java-programming.mooc.fi › part-11 › 3-exceptions
Exceptions - Java Programming
The user input, in this case the string no!, is given to the Integer.parseInt method as a parameter. The method throws an error if the string cannot be parsed into an integer. Note, that the code within the catch block is executed only if an exception is thrown.
Top answer
1 of 2
2

Your field is empty and you are trying to convert an empty string into a number (via parseInt()). That's what is causing the NumberFormatException.

To avoid that kind of exception, you should validate your field. You can write a simple check testing if it's empty by asserting that the length() of the input String returned by getText() is greater than zero.

You can check if it is a number writing a regular expression

String possibleNumber = yourField.getText();
boolean isNumber = Pattern.matches("[0-9]+", possibleNumber);
if(isNumber) {
   number = Integer.parseInt(possibleNumber);
}

But you shouldn't be reading data in the constructor in the first place. Write an event handler to capture the action event of pressing the button, and in it read the data.

yourButton.addActionListener(new ActionListener() {
    yourText = field.getText();
}); 
2 of 2
2

This exception say :

java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)

your input string here is set to "" aka an empty String and then you try to parse the "" into an int. And that is not possible and therefore the error.

Make sure you pass in correct numbers like 1 2 3 or something and with no dots like 1.2 because that aswell will give an error.

You should also add some logic so its not possible to pass in an empty string or catch the empty string or a double value. Because it will cause this exception everytime user does not input a correct number format.