Casting the left and right numbers as integers or doubles How can I remove the code duplication in this code? It is trying to cast the left and right numbers as integers or doubles and then using it.

public Object example(Object left, Object right) {
    if(left instanceof Integer &amp;&amp; right instanceof Integer) {
        switch (operator) {
            case ADD:
                return (Integer)left + (Integer)right;
            case SUB:
                return (Integer)left - (Integer)right;
            case MUL:
                return (Integer)left * (Integer)right;
            case DIV:
                return (Integer)left / (Integer)right;
        }
    } else if(left instanceof Double &amp;&amp; right instanceof Double) {
        switch (operator) {
            case ADD:
                return (Double)left + (Double)right;
            case SUB:
                return (Double)left - (Double)right;
            case MUL:
                return (Double)left * (Double)right;
            case DIV:
                return (Double)left / (Double)right;
        }
    } else {
        throw new Error("wrong types of arguments");
    }
}
One option would be to do your math operations on a double.  You can use a generic method that accepts any derivative of the Number class and use the doubleValue() method for your calculation.  The caller of the method can cast to Integer as needed:

enum Operators {
    ADD,
    SUB,
    MUL,
    DIV
}

public static &lt;T1 extends Number&gt; Double doMath(T1 left, T1 right, Operators operator) {
    switch (operator) {
        case ADD:
            return left.doubleValue() + right.doubleValue();
        case SUB:
            return left.doubleValue() - right.doubleValue();
        case MUL:
            return left.doubleValue() * right.doubleValue();
        case DIV:
            return left.doubleValue() / right.doubleValue();
        default:
            return 0.0;
    }
}