Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <pre><code>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 &lt; s.length(); i++) { if(i == 0 &amp;&amp; s.charAt(i) == '-') { if(s.length() == 1) return false; else continue; } if(Character.digit(s.charAt(i),radix) &lt; 0) return false; } return true; } </code></pre> <p>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.</p> <pre><code>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(); } </code></pre> <p>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:</p> <pre><code>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; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload