Thinking Java
Sunday, February 12, 2006
  Precedence and Associativity Rules for Variables
Precedence Rules are used to determine which operator should be applied first if there are two or more operators with different precedence in the expression.
Associativity Rules are used to determine which operator should be applied first if there are two or more operators with the same precedence in the expression.
Precedence and Associativity Rules together determine in what order the varibles are evaluated in an expression

Operator Type Operators Associativity
Postfix Operators [] . (parameters) x++ x-- Unary postfix increment and decrement operators associate left to right, other unary operators associate right to left
Unary prefix operators ++x --x +x -x ~ ! Right to left
Unary prefix creation and cast new (type) Right to left
Multiplicative * / % Left to right
Additive + - Left to right
Shift << >> >>> Left to right
Relational < <= > >= instanceof Non Associative
Equality == != Left to right
Bitwise/Logical AND & Left to right
Bitwise/Logical XOR ^ Left to right
Bitwise/Logical OR | Left to right
Conditional AND && Left to right
Conditional OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= <<= >>= >>>= &= ^= |= Right to left

Java guarantees that all operands of an operator are fully evaluated before the operator is applied. The only exceptions are the short-circuit conditional operators &&, ||, and ?:
In the case of the a binary operator, if the left hand operand causes an exception, the right-hand operand is not evaluated
 
Comments:
everything is allright but could u plz varify my o/p with the hereby claimed information.
a=1;
System.out.println(++a+a--);
O/p: 4.
in the Expression operators are
++exp,exp-- and binary +
step1:HIGHEST PRIORITY OPERATOR
IS exp-- so expn becomes
++a+1
& a=0
step2:
now expn becomes 1+1 i.e 2
and a=1.
so how can it be 4.
 
let's see:
++a+a--
by applying precedence rules
(++a)+(a--)
lhs is always evaluated before rhs
2+(a--) ; a=2

2+2 ; a=1

4
 
This comment has been removed by the author.
 
Post a Comment



<< Home

Name:
Location: Santa Barbara, California, United States

This blog is an attempt to present a coherent view of life in progress as much to myself as to others unfortunate enough to come across it...

ARCHIVES
February 2006 / March 2006 / May 2006 /


Powered by Blogger