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.

People also ask

How to handle exceptions with parseInt() in Java?
Wrap the parseInt() call inside a try-catch block to catch NumberFormatException. This ensures your program doesn’t crash when invalid or unexpected input is passed for conversion.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › parseint in java
parseInt in Java: Everything You should Know | upGrad
What are the parameters of parseInt() in Java?
The parseInt() method in Java accepts either one or two parameters: A string containing digits An optional radix (base), like 2 for binary or 16 for hexadecimal Both forms convert the string to an int based on the specified base.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › parseint in java
parseInt in Java: Everything You should Know | upGrad
How does Integer.parseInt() work in Java?
Integer.parseInt() in Java takes a string as input and returns its integer value. If the string is not a valid integer, it throws a NumberFormatException. It’s ideal for parsing numbers from user input or text files.
🌐
upgrad.com
upgrad.com › home › tutorials › software & tech › parseint in java
parseInt in Java: Everything You should Know | upGrad
🌐
Scaler
scaler.com › home › topics › parseint() in java
parseInt() in Java - Scaler Topics
May 8, 2024 - It is used in java for converting a string value to an integer by using the method parseInt(). The parseInt() method throws three exceptions: NullPointerException, IndexOutOfBoundsException, NumberFormatException when the input arguments are ...
🌐
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...
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › parseint in java
parseInt in Java: Everything You should Know | upGrad
June 25, 2025 - The exception is caught in a try-catch block, and a corresponding error message is printed. It's important to handle the NumberFormatException appropriately in your code, as it indicates that the string could not be parsed as an integer.
🌐
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").
🌐
Tutorialspoint
tutorialspoint.com › java › lang › integer_parseint.htm
Java - Integer parseInt() method
package com.tutorialspoint; public class IntegerDemo { public static void main(String[] args) { String str = "0x3"; /* returns an Integer object holding the int value represented by string str */ System.out.println("Number = " + Integer.parseInt(str)); } } Let us compile and run the above program, this will produce the following result − · Exception in thread "main" java.lang.NumberFormatException: For input string: "0x3" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at java.lang.Integer.parseInt(Unknown Source) at com.tutorialspoint.IntegerDemo.main(IntegerDemo.java:10)
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.
🌐
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.
🌐
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 ...
🌐
Reddit
reddit.com › r/javahelp › integer.parseint() is bugging out on me
r/javahelp on Reddit: Integer.parseInt() is bugging out on me
December 26, 2017 -

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!

🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.lang.integer.parseint
Integer.ParseInt Method (Java.Lang) | Microsoft Learn
The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u005Cu002D') to indicate a negative value or an ASCII plus sign '+' ('\u005Cu002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the #parseInt(java...
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › lang › Integer.html
Integer (Java Platform SE 7 )
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.
🌐
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.
🌐
JanBask Training
janbasktraining.com › community › java › explain-the-java-parseint-exception
Explain the Java parseint exception? | JanBask Training Community
October 10, 2022 - String strCorrectCounter = element.getAttribute("correct"); Integer iCorrectCounter = new Integer(0); try { iCorrectCounter = new Integer(strCorrectCounter); } catch (Exception ignore) { } Answered by Alison Kelly · here is a solution regarding the Java parseint exception: int tryParseInt(String value) { try { return Integer.parseInt(value); } catch(NumberFormatException nfe) { // Log exception.
🌐
GeeksforGeeks
geeksforgeeks.org › java › numberformatexception-in-java-with-examples
NumberFormatException in Java with Examples - GeeksforGeeks
July 23, 2025 - It is a subclass of IllegalArgumentException class. To handle this exception, try-catch block can be used. While operating upon strings, there are times when we need to convert a number represented as a string into an integer type. The method generally used to convert String to Integer in Java is parseInt().