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.

🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.lang.integer.parseint
Integer.ParseInt Method (Java.Lang) | Microsoft Learn
The resulting integer value is returned. An exception of type NumberFormatException is thrown if any of the following situations occurs: <ul> <li>The first argument is null or is a string of length zero.
🌐
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...
🌐
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!

🌐
Dot Net Perls
dotnetperls.com › parseint-java
Java - parseInt: Convert String to Int - Dot Net Perls
ParseInt can lead to complex problems—it throws a NumberFormatException on invalid data. Many exceptions will lead to slower program performance.
Find elsewhere
🌐
Coderanch
coderanch.com › t › 393405 › java › Integer-parseInt-NumberFormatException
Integer.parseInt : NumberFormatException (Beginning Java forum at Coderanch)
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"). The error also occurs if string is "1".
🌐
Rollbar
rollbar.com › home › how to handle the numberformatexception in java
How to Handle the NumberFormatException in Java | Rollbar
June 29, 2025 - There are several strategies to handle this exception effectively: public class SafeNumberParsing { public static void main(String[] args) { String input = "12a"; try { int number = Integer.parseInt(input); System.out.println("Parsed number: " + number); } catch (NumberFormatException e) { System.out.println("Invalid number format: " + input); // Log the exception or provide user feedback } System.out.println("Program continues normally..."); } } Output: Invalid number format: 12a Program continues normally...
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › lang › Integer.html
Integer (Java Platform SE 7 )
public static int parseInt(String s) throws NumberFormatException · Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.
🌐
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.
🌐
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.
🌐
Javatpoint
javatpoint.com › java-integer-parseint-method
Java Integer parseInt() Method - Javatpoint
Java Program to use Finally Block for Catching Exceptions · Count Login Attempts Java · Largest Independent Set in Java · Longest Subarray With All Even or Odd Elements in Java · Open and Closed Hashing in Java · DAO Class in Java · Kynea Numbers in Java · UTF in Java · Zygodromes in Java · ElasticSearch Java API · Form Feed in Java · Java Clone Examples · Payment Gateway Integration in Java ·
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › parseint in java
parseInt in Java: Everything You should Know | upGrad
June 25, 2025 - The parseInt() method in Java can throw a NumberFormatException if the string cannot be parsed as an integer. Here are the common causes of this exception: The string contains characters other than digits and an optional leading minus sign (-) ...