Validator for mathematical expressions in infix notation The function belows validates if a mathematical expression, say 12 + 2 * (9 - 3) / 4, does not have operators that are next to each other. It returns false if an operator is next to another operator. Otherwise, it returns true. For example, if the input expression is 2++1, it will return false. The function also recursively evaluates expressions that are inside pairs of parentheses.

private boolean validateOperators(String expression)
{
    if (!validateEndCharacters(expression)) {
        return false;
    }

    Stack s = new Stack(15); // Stack is a user-defined class.
    char[] operators = { '+', '-', '*', '/' };
    char prevOperator = '\0';
    String subexpression = "";
    boolean addSubexpression = false;
    boolean isValid = false;

    for (char c : expression.toCharArray()) {
        if (addSubexpression) {
            if (c == '(') {
                s.push("(");
            } else if (c == ')') {
                s.pop();
                if (s.isEmpty()) {
                    // We found the end of the expression inside the parentheses.
                    isValid &amp;= this.validateOperators(subexpression);
                    subexpression = "";
                    prevOperator = '\0';
                    addSubexpression = false;
                }
            }

            subexpression += Character.toString(c);
        } else {
            if (c == '(') {
                addSubexpression = true;
                s.push("(");
            } else if (this.isIn(c, operators) &amp;&amp; prevOperator == '\0') {
                prevOperator = c;
            } else if (this.isIn(c, operators) &amp;&amp; prevOperator == '\0') {
                isValid &amp;= false;
                break;
            } else if (Character.isDigit(c)) {
                prevOperator = '\0';
            }
        }
    }

    if (!s.isEmpty()) {
        return false;
    }

    return isValid;
}

private boolean validateEndCharacters(String expression)
{
    char[] operators = { '+', '-', '*', '/' };
    if (this.isIn(expression.charAt(0), operators) ||
       this.isIn(expression.charAt(expression.length() - 1), operators)) {
        return false;
    }

    return true;
}


How else can I improve the functions?
You can already reuse operators in each methods by making it a constant. You can create a Set and use the containsmethod instead of this.isIn.

You can simplify validateEndCharacters, if ( condition ) { return true } else { return false } can always be simplified by return condition.

The two else if looks like the second block will never be executed :

...
} else if (this.isIn(c, operators) &amp;&amp; prevOperator == '\0') {
    prevOperator = c;
} else if (this.isIn(c, operators) &amp;&amp; prevOperator == '\0') {
    isValid &amp;= false;
    break; 
}