+ 9
In java what does it mean by operators associativity?
In java, according to my textbook, operators follow a specific type of associativity, for example: Operators *,/,% have associativity L to R. While, Operators +, - have associativity R to L. I have no idea about what does it mean.
5 Answers
+ 13
SOLO FREAK
try mine given examples on code-playground of java
//yeah ,above information is correct , might typo error in your book[no doubt]
//btw there is something called "Precedence" also & using it along with "Associativity" means U will never be confused in output of any expression âș
+ 20
operators with associativity from left to right :
*,/,%,+,-,logical operators(&&,||) ,equality operators(==,!=),bitwise operators(&,^,|), shift operator(>>,>>>,<<) etc
example : int y=9/3/3;
//here it can be treated as (9/3)/3 =1 , not 9/(3/3) =9 because associativity of / operator is from left to right
operators with associativity from right to left :
assignment operator (=, +=,%=,^= etc), ternary operators(? :),cast operator(( )),new operator etc
example :
int b=1;c=2;
int a=b=c; //a will be 2 , not 1 because it can be treated as int a=(b=c); as assignment operator(=) have precedence from right to left
operators with no associativity :
relational operators(>,<,<= etc) , unary post increment-decrement operator(x++,x--) are non-associative
example -
x++--; // will be non-associative & will cause error
boolean bol=(a<b<c); //it is also invalid
[very helpful information, it is from a lesson I made (might pending) âș]
//đ
+ 3
Thanks Gaurav Agrawal !!
Just there is still one confusion.
The operators namely, relational and increment-decrement operators, are clearly non associative from your examples (which I agree with) but my textbook says they too have associativity!!
here what's written in it:
Relational operators have L to R associativity and increment-decre ment operators have R to L associativity
what do you think?
Personally I still think you are correct, but still...
+ 2
Ok
+ 2
From what I understand, the direction of associativity of an operator is going to determine the order of operation in a statement containing multiple operators of the same precedence.
For example, in (3 - 2 - 1 + 2), the output should be 2, because it is interpreted as (((3 - 2) - 1) + 2), with L to R associativity.
If it were the other way around, the equation would become (3 - (2 - (1 + 2))) and would evaluate to 4.