350

I'm trying to determine if a particular item in an Array of strings is an integer or not.

I am .split(" ")'ing an infix expression in String form, and then trying to split the resultant array into two arrays; one for integers, one for operators, whilst discarding parentheses, and other miscellaneous items. What would be the best way to accomplish this?

I thought I might be able to find a Integer.isInteger(String arg) method or something, but no such luck.

3
  • I do not understand with several java updates, such easy helper methods are not being made built in into the kit.
    – tony9099
    Commented Sep 30, 2013 at 14:08
  • @tony9099 it's kind of an edgecase situation and, from what I've seen slash the fact that this question still gets views, fairly unique. The accepted workaround (that I accepted as an answer) is probably better than making it Java standard. Commented Oct 2, 2013 at 22:59
  • 2
    @Nick to further your argument that it's not necessary to be in Java, only about one in every 772 visitors decided to vote up my answer, despite there being three useful solutions (admittedly, each better than the previous one). I think that is a clear indicator this is an edge case where in most cases you're better off changing the way you solve the problem such that you don't need my solution instead of actually using it.
    – corsiKa
    Commented Oct 4, 2013 at 16:22

9 Answers 9

363

The most naive way would be to iterate over the String and make sure all the elements are valid digits for the given radix. This is about as efficient as it could possibly get, since you must look at each element at least once. I suppose we could micro-optimize it based on the radix, but for all intents and purposes this is as good as you can expect to get.

public static boolean isInteger(String s) {
    return isInteger(s,10);
}

public static boolean isInteger(String s, int radix) {
    if(s.isEmpty()) return false;
    for(int i = 0; i < s.length(); i++) {
        if(i == 0 && s.charAt(i) == '-') {
            if(s.length() == 1) return false;
            else continue;
        }
        if(Character.digit(s.charAt(i),radix) < 0) return false;
    }
    return true;
}

Alternatively, you can rely on the Java library to have this. It's not exception based, and will catch just about every error condition you can think of. It will be a little more expensive (you have to create a Scanner object, which in a critically-tight loop you don't want to do. But it generally shouldn't be too much more expensive, so for day-to-day operations it should be pretty reliable.

public static boolean isInteger(String s, int radix) {
    Scanner sc = new Scanner(s.trim());
    if(!sc.hasNextInt(radix)) return false;
    // we know it starts with a valid int, now make sure
    // there's nothing left!
    sc.nextInt(radix);
    return !sc.hasNext();
}

If best practices don't matter to you, or you want to troll the guy who does your code reviews, try this on for size:

public static boolean isInteger(String s) {
    try { 
        Integer.parseInt(s); 
    } catch(NumberFormatException e) { 
        return false; 
    } catch(NullPointerException e) {
        return false;
    }
    // only got here if we didn't return false
    return true;
}
29
  • 4
    The "non exception based method" will consider "-" to be an integer. Commented Sep 5, 2012 at 15:45
  • 6
    It certainly is an unorthodox way to do it. As general rule, you want to avoid using exceptions to dictate execution flow. Or as Joshua Bloch puts it in his "Effective Java item 57: Use exceptions only for exceptional conditions." His comment on using exceptions to iterate over an array is // Horrible abuse of exceptions. Don't ever do this! actually
    – corsiKa
    Commented Mar 3, 2015 at 17:53
  • 4
    Could somebody explain to me why the 3rd method is bad practice? Because of basing the execution flow on exceptions? Commented May 24, 2015 at 17:10
  • 67
    They're called "exceptions" for a reason. In a perfect world, you never get an exception. Say my boss asks me to work on an assignment. He'll expect me to say "yes, sir!" but I might reply with "I have a lot on my plate right now, I can't accept a new assignment without letting existing work fall through." He is prepared for both of those. He isn't prepared for me to punch him in the face. I lose my job and he calls security. Now imagine if he called security for me simply saying I have too much work - that's the third method: calling the cops for something that should just be expected.
    – corsiKa
    Commented May 24, 2015 at 22:40
  • 8
    Using the non exception method the string "9999999999999999999999" is a valid integer
    – fgonzalez
    Commented Dec 3, 2016 at 9:49
315

It's better to use regular expression like this:

str.matches("-?\\d+");

-?     --> negative sign, could have none or one
\\d+   --> one or more digits

It is not good to use NumberFormatException here if you can use if-statement instead.

If you don't want leading zero's, you can just use the regular expression as follow:

str.matches("-?(0|[1-9]\\d*)");
7
  • 17
    Also... If anyone wants to deal with the signal '+', I made that version (Regarding to yours) : str.matches("^[+-]?\\d+$")
    – Damiii
    Commented Apr 9, 2015 at 10:46
  • 19
    Curious as to why this isn't the chosen answer... Commented Jun 2, 2015 at 0:04
  • 8
    @BrentHronik It's a nice clean one-liner, but according to one of the answers at stackoverflow.com/questions/237159/…, it's 10x slower than the methods suggested by corsiKa.
    – lreeder
    Commented Jul 5, 2015 at 15:04
  • 2
    I downvoted. Reason: The question is to check whether the given string is integer or not. The integer has a limit for number of digits ranging -2147483648 to 2147483647. If you provide more char in your string than the limit, regex will pass it.
    – smilyface
    Commented Jun 10, 2022 at 8:34
  • 1
    @smilyface, exactly. I would understand why people blame using exceptions if Java had isInt method and someone still used parseInt for checking int via exceptions. Unfortunately, there is no other method for that, and given how many validations parseInt is performing for us, implementing custom methods just to "avoid exceptions" or "fitting best practices" is nothing but over-engineering in the best case. As we know sometimes doing X instead of Y is better although Y is preffered in general. Commented Apr 25, 2023 at 11:09
163

Or you can enlist a little help from our good friends at Apache Commons : StringUtils.isNumeric(String str)

6
  • 3
    The only question I have about this method is "" returning true. Our intuition tells us that the empty string is not a number (Integer for the OP question) you can perform mathematical operations on, but I guess you can say you cannot prove that the empty string is non-numeric because we haven't told you yet what the String will be.
    – demongolem
    Commented Dec 16, 2011 at 17:02
  • 18
    I wish this was a good answer for me, but not only does "" return true but also "-1" will return false. That means that it will neither return true for all valid integers nor will the fact that it returns true guarantee that passing it to Integer.parseInt will not throw an exception.
    – jhericks
    Commented Apr 4, 2013 at 2:41
  • 5
    @jhericks Thanks for pointing that out. When I first answered this a couple of years ago it was referencing an older version of Commons StringUtils. They have since updated the api such that empty string is now considered non-numeric. Unfortunately the negative case would have to be handled separately which is a drawback but the work around is trivial. Simply a check for numberCandidate.startsWith("-") and a substring call with a negation after the parseInt call assuming the value was numeric of course. Commented Apr 5, 2013 at 7:14
  • 4
    Not only is StringUtils.isNumeric(String) not fulfilling the original request to check if a string "is an integer or not", but also suggesting a beast like the apache commons in order to avoid writing a one-liner is not rational imho. Commented Jul 8, 2017 at 22:27
  • Just avoid Apache "commons" at all costs. While sometimes a good idea at first sight, it's just a bunch of antipatterns that will bring you dependency hell, for debatable results.
    – ymajoros
    Commented Oct 4, 2017 at 5:20
80

Or simply

mystring.matches("\\d+")

though it would return true for numbers larger than an int

6
  • 8
    doesn't work. matches any string that contains 1 or more digits in a row. for example, blabla. 0 bla bla bla matches.
    – njzk2
    Commented Sep 13, 2013 at 14:38
  • 15
    @njzk2 use "^-?\\d+$" as your regex
    – Sujay
    Commented Sep 18, 2013 at 13:42
  • 2
    what about values x with x > Integer.MaxValue, same for min? Commented Oct 19, 2016 at 9:13
  • njzk2 - it does work because String.matches() only returns true if the whole string matches the pattern, though you have to follow the documentation trail from String.matches() to Pattern.matches() to Matcher.matches() to discover that fact.
    – Shon Vella
    Commented Jun 1, 2017 at 22:25
  • Works fine for numbers less than Integer.MaxValue. This solution shows bad performance though. Have a look at the benchmark here: baeldung.com/java-check-string-number
    – javadev
    Commented Dec 19, 2019 at 17:56
78

You want to use the Integer.parseInt(String) method.

try{
  int num = Integer.parseInt(str);
  // is an integer!
} catch (NumberFormatException e) {
  // not an integer!
}
4
  • 4
    Why is this not higher rated? It seems the simplest to me, or are there some downsides I am missing? Commented Apr 14, 2016 at 8:14
  • 16
    @bobismijnnaam The problem with this is, that it generates a relative expensive exception and you have some nasty nesting, which may affect readability.
    – Zhedar
    Commented Apr 20, 2016 at 19:29
  • 8
    Exceptions are indicating that something went wrong, and this kind of usage surely is an abuse of this design principle. Only use Integer.parserInt() after you ensured, that the String really contains an integer value. If doing so and Integer.parseInt still throws an exception, then you know that you have a problem in your code which you should fix (or, for the sake of completeness, that Integer.parseInt itself is buggy, but this option is quite unlikely)
    – Rolch2015
    Commented Sep 1, 2016 at 20:18
  • not worked and converted aaaa into some value Commented Mar 15, 2019 at 4:55
16

As an alternative approach to trying to parse the string and catching NumberFormatException, you could use a regex; e.g.

if (Pattern.compile("-?[0-9]+").matches(str)) {
    // its an integer
}

This is likely to be faster, especially if you precompile and reuse the regex.

However, the problem with this approach is that Integer.parseInt(str) will also fail if str represents a number that is outside range of legal int values. While it is possible to craft a regex that only matches integers in the range Integer.MIN_INT to Integer.MAX_INT, it is not a pretty sight. (And I am not going to try it ...)

On the other hand ... it may be acceptable to treat "not an integer" and "integer too large" separately for validation purposes.

10

You can use Integer.parseInt(str) and catch the NumberFormatException if the string is not a valid integer, in the following fashion (as pointed out by all answers):

static boolean isInt(String s)
{
 try
  { int i = Integer.parseInt(s); return true; }

 catch(NumberFormatException er)
  { return false; }
}

However, note here that if the evaluated integer overflows, the same exception will be thrown. Your purpose was to find out whether or not, it was a valid integer. So its safer to make your own method to check for validity:

static boolean isInt(String s)  // assuming integer is in decimal number system
{
 for(int a=0;a<s.length();a++)
 {
    if(a==0 && s.charAt(a) == '-') continue;
    if( !Character.isDigit(s.charAt(a)) ) return false;
 }
 return true;
}
3

You can use Integer.parseInt() or Integer.valueOf() to get the integer from the string, and catch the exception if it is not a parsable int. You want to be sure to catch the NumberFormatException it can throw.

It may be helpful to note that valueOf() will return an Integer object, not the primitive int.

6
  • edited for clarity. No need to be cheeky. Commented Mar 26, 2011 at 1:41
  • @krmby the objective is not to actually retrieve the value, only to determine if it fits the format. In that regard, Chad is correct in that both of the methods will work just fine.
    – corsiKa
    Commented Mar 28, 2011 at 18:35
  • @glowcoder you are talking about edited version of the answer which i am not. I now both methods do the job fine but this does not change the fact that return type of Integer.parseInt() is int. Commented Mar 29, 2011 at 11:21
  • @krmby ah an interesting point. I was focusing on the first paragraph (which as I review, remains unchanged.)
    – corsiKa
    Commented Mar 29, 2011 at 16:28
  • @glowcoder Author of this answer said: It may be helpful to note that those methods will return an Integer object, not the primitive int. I'm ONLY saying that parseInt() returns int. I said NOTHING about first paragraph. Chad La Guardia CORRECTED his answer according to my comment and everything is fine. So i'm not getting your point actually. Commented Mar 29, 2011 at 17:23
0
public boolean isInt(String str){
    return (str.lastIndexOf("-") == 0 && !str.equals("-0")) ? str.substring(1).matches(
            "\\d+") : str.matches("\\d+");
}
2
  • 1
    This will also return true for the string ---0--- which surely is not int.
    – Matthias
    Commented Oct 16, 2013 at 8:49
  • @Matthias You are right i haven't tested it, I edited my answer to check for that now
    – Titus
    Commented Oct 16, 2013 at 23:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.