Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Operator Precedence Comparison

Tags:

java

Does java have a built-in method to compare precedence of two operators? For example, if I have a char '/' and a char '+' is there a method I can call that compares the two and returns true/false if the first is greater than the second (e.g. true)?

like image 353
Andrew Keller Avatar asked Apr 30 '10 03:04

Andrew Keller


People also ask

Which operator in Java has highest precedence?

In Java, parentheses() and Array subscript[] have the highest precedence in Java. For example, Addition and Subtraction have higher precedence than the Left shift and Right shift operators.

Which has more precedence || or &&?

The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- .


2 Answers

Operator precedence the way you defined it, while common, is not a universal truth that the Java language should recognize. Therefore no, Java language itself does not have such comparison. It is of course easy to write your own:

int precedenceLevel(char op) {
    switch (op) {
        case '+':
        case '-':
            return 0;
        case '*':
        case '/':
            return 1;
        case '^':
            return 2;
        default:
            throw new IllegalArgumentException("Operator unknown: " + op);
    }
}

Then given char op1, op2, just compare precedenceLevel(op1), precedenceLevel(op2).

You can also use if-else, or ternary operators instead of switch if you only have very few operators. Another option would be to use an enum Operator implements Comparable<Operator>, but depending on what you're doing, perhaps a parsing tool like ANTLR is the better.


Note that the above example puts ^ at the highest precedence, implying that perhaps it's used to denote exponentiation. In fact, ^ in Java language is the exclusive-or, and it has a lower precedence than +.

    System.out.println(1+2^3);   // prints 0
    System.out.println(1+(2^3)); // prints 2
    System.out.println((1+2)^3); // prints 0

This just goes to show that the precedence and even semantics of these symbols are NOT universal truths.

See also:

  • What does the ^ operator do in Java?
like image 54
polygenelubricants Avatar answered Sep 19 '22 18:09

polygenelubricants


no. your best bet is to find a 3rdparty jar that does language parsing, and see if they have methods such as that.

like image 40
MeBigFatGuy Avatar answered Sep 20 '22 18:09

MeBigFatGuy