Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Operator Associativity

 
Saniya Ansari
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Dan (specially coz i'm doign ur mock exams), I tried this question in Exam D:
class L {
public static void main (String s[]) {
int i = 1 | 2 ^ 3 * 2 & 13 | 2;
System.out.println(i%5);
}
}
The answer is 2. Your explanation is also helpful.. i'm wondering are there any rules to follow when we evaluate such an expression. It is left associative but how shoudl we group them.. i.e how do we get (1 | (2 ^ ((3 * 2) & 13)) | 2)
instead of some other arrangement.
So someone can help?!
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please see the following tutorial and operator precedence chart.
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/expressions.html
I hope that helps.
 
Wena Dollison
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just remember these abbreviation:
U - Unary
A - Arithmetic
S - Shift
C - Comparison
B - Bitwise
S - Short-Circuit
C - Conditional
A - Assignment
So unary operators come first, then arithmetic operators, and so on. * always come first in the arithmetic operators (if not grouped or within parentheses or associated) and & then ^ then | is the order for the Bitwise operators
You can also read this in RHE Java Certification book
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic