7

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)?

Andrew Keller
  • 3,198
  • 5
  • 36
  • 51

4 Answers4

14

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:

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
2

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

MeBigFatGuy
  • 28,272
  • 7
  • 61
  • 66
0

You can write you own API, which performs this and Send this as a parameter and gives you the result.

gmhk
  • 15,598
  • 27
  • 89
  • 112
0

I am puzzled why you think you need this information at run-time. In every language I have ever used including algebra and English, operator precedence is predefined.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Hi- I know this is very old but I haven't logged in recently. The question was for a school assignment involving a prefix to postfix converter. Since the prefix expression is provided by the user, then the order of operations needed to be defined in a function so operations in the user-provided prefix could be evaluated at runtime. – Andrew Keller Jun 24 '10 at 03:55
  • That doesn't make sense. Unless the operator precedence is defined by the user, it can be hardcoded into the structure of the program. – user207421 Jun 25 '10 at 00:23