Java Operator Precedence Table and Examples - Quiz
Total: 5 questions
1. How do the bitwise operators &, ^ and | rank by precedence?
How do the bitwise operators &, ^ and | rank by precedence?
The order is & > ^ > |. Bitwise AND (&) binds tighter than exclusive OR (^), which binds tighter than inclusive OR (|). So in 6 | 1 ^ 3 & 2 the 3 & 2 is evaluated first, then the ^, and the | last.
2. What is the associativity of the ternary operator ? :, and how does a ? b : c ? d : e group?
What is the associativity of the ternary operator ? :, and how does a ? b : c ? d : e group?
The ternary operator is right-associative and has very low precedence. a ? b : c ? d : e parses as a ? b : (c ? d : e) — the nested ternary goes into the "else" branch. Handy for chaining conditions, but add parentheses when nesting to keep it readable.
3. If operator precedence is already fixed by the language, why add parentheses?
If operator precedence is already fixed by the language, why add parentheses?
Parentheses are for humans, not the compiler. Precedence is unambiguous, but code is read by colleagues who do not recall all 15 levels by heart. Explicit parentheses in (a && b) || c or (x & y) == 0 remove doubt, prevent mistakes during edits, and make intent obvious. Relying on precedence in tricky mixes (bitwise + comparisons, shifts + arithmetic) is a frequent source of bugs.
4. How does obj instanceof String && flag group, and why?
How does obj instanceof String && flag group, and why?
It groups as (obj instanceof String) && flag. The instanceof operator is relational (same level as < > <= >=) and outranks the logical &&. So the type check runs first, and its boolean result then feeds into &&. The parentheses are optional here but improve readability.
5. What precedence does a type cast (Type) have relative to arithmetic, and what does that mean in practice?
What precedence does a type cast (Type) have relative to arithmetic, and what does that mean in practice?
A cast is a high-precedence unary operation (above * / % and + -). It binds only to the operand immediately following it, not to the whole expression. So (int) 5.9 + 0.1 means ((int) 5.9) + 0.1 = 5 + 0.1 = 5.1, not (int)(5.9 + 0.1). To cast the whole result you need parentheses: (int)(a + b).