How can I check if a String is an integer in Java?

Hey, Devan! That regex method is great, but here’s another cool one you might not have considered: using the Scanner class. It’s part of the built-in Java functionality and doesn’t rely on regex or exceptions, which is pretty neat for simple tasks.

Here’s how you can do it:

import java.util.Scanner;

public static boolean isIntegerScanner(String str) {
    Scanner scanner = new Scanner(str);
    boolean isInt = scanner.hasNextInt();
    scanner.close();
    return isInt;
}

public static void main(String[] args) {
    System.out.println(isIntegerScanner("123"));   // true
    System.out.println(isIntegerScanner("-456"));  // true
    System.out.println(isIntegerScanner("3.14"));  // false
    System.out.println(isIntegerScanner("abc"));   // false
}

:white_check_mark: Why use this?

  • Utilizes built-in functionality, so no need for extra dependencies like regex.
  • It handles leading and trailing spaces gracefully, which can be pretty handy in real-world applications.

:warning: When NOT to use this:

  • If you’re trying to avoid the overhead of creating a new Scanner instance each time, it might be a bit overkill for small checks.

But hey, it’s definitely one of those underused tricks that works well when you’re already working with scanners or just need a quick check.