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)?
Does java have a built-in method to compare precedence of two operators? For example,
Share
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:
Then given
char op1, op2, just compareprecedenceLevel(op1), precedenceLevel(op2).You can also use
if-else, or ternary operators instead ofswitchif you only have very few operators. Another option would be to use anenum 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+.This just goes to show that the precedence and even semantics of these symbols are NOT universal truths.
See also: