instanceof use for multiple types

instanceof, integer, java

Solution

`instanceof` is a binary operator: it can only have two operands.

The best solution for your problem is Java's boolean AND operator: `&&`.

It can be used to evaluate two boolean expressions: `<boolean_exp1> && <boolean_exp2>`. Will return `true` if and only if both are `true` at the time of the evaluation.

if (n.e1.accept(this) instanceof Integer &&
    n.e2.accept(this) instanceof Integer) {
    ...
}

That being said, another possible solution is to cast them both inside a `try`/`catch` block, and when one of them is not an `Integer` a `ClassCastException` will be thrown.

try {
   Integer i1 = (Integer) n.e1.accept(this);
   Integer i2 = (Integer) n.e2.accept(this);
} catch (ClassCastException e) {
   // code reached when one of them is not Integer
}

But this is not recommended as it is a known anti-pattern called Programming By Exception.

We can show you a thousand ways (creating methods, creating classes and using polymorphism) you can do that with one line, but none of them will be better or clearer than using the `&&` operator. Anything other than that will make you code more confusing and less maintainable. You don't want that, do you?

Problem

I am writing a TypeChecker for MiniJava and ExpOp needs to check if both of the entered expressions are of Integer to use plus, minus, times. How can I write a line of code inside an `if` statement that includes both expressions and checks if both of them are instances of (`instanceof`) `Integer`? This is what I have now: ``` n.e1.accept(this) n.e2.accept(this) instanceof Integer ``` Appreciate your help.

Original source