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

I’m processing an infix expression by splitting a String into an array using .split(" "). I need to separate integers and operators while discarding parentheses and other symbols. Does Java provide a built-in way to java check if string is integer, or do I need a custom implementation?

Alright, if you’re looking for a simple and quick way to check if a string is an integer in Java, one of the go-to methods is using Integer.parseInt() inside a try-catch block. This is a pretty straightforward approach, especially when you’re sure that the input is either a valid integer or invalid.

Here’s how you can implement it:

public static boolean isInteger(String str) {
    try {
        Integer.parseInt(str);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

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

:white_check_mark: Why use this?

  • It’s really simple and quick to implement.
  • Handles both positive and negative integers.
  • No need for regex or extra dependencies.

:warning: When NOT to use this:

  • If you want to handle larger numbers that exceed Integer.MAX_VALUE (this will throw an exception).
  • Or, if you want to avoid using exceptions as a part of your flow control.

But this is definitely my go-to for smaller tasks.

Totally agree with Emma! If you’re looking to avoid exceptions and prefer something more declarative, using regular expressions is another great option. It ensures the string strictly follows an integer format, so you don’t get caught up in exception handling.

Here’s how you can use regex to java check if string is integer:

public static boolean isIntegerRegex(String str) {
    return str.matches("-?\\d+");
}

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

:white_check_mark: Why use this?

  • No exceptions involved; it’s just a clean boolean check.
  • The pattern is pretty readable if you’re familiar with regex.
  • This method is awesome for validating user input where performance isn’t a top concern.

:warning: When NOT to use this:

  • If you’re not a fan of regex (it can sometimes be a little tricky to debug).
  • And performance might be an issue; regex tends to be slower than just parsing the string directly.

So, if you’re comfortable with regex and prefer pattern matching, this is a solid choice.

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.