• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Associativity(Left or Right)

 
Swamy Nathan
Ranch Hand
Posts: 187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello there!
What is the associativity of expr++ and expr--?
Also what is the associativity of == and !=?
Thanks.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's a table of java operations that will help you.
 
Sandeep Advani
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Unfortunately Barry, that page gives me an access forbidden ! Could you rectify the problem and inform us when the link is up and working. Thanks.

Sandeep
 
Swamy Nathan
Ranch Hand
Posts: 187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was studying from the Khalid book.
It says that relational operators i.e. < <= > >= instanceof are non-associative

But in the table you pointed to in ur URL- it says that the associativity is LEFT.

So who do I believe?



The Khalid booik was vague about the associativity of the == and != operators. (I could not figure it out.)
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sandeep, I have no control over that link, sorry.

Swarmy, I have Mughal's 1.4 book here and it is rather confusing. At one point on page 67 he says "Relational operators are nonassociative." and then five lines later he says "since relational operators have left associativity"! So the best thing is to get the hands dirty and try things out!

If you compile the following:

the compiler objects with:



This means that the compiler is using left associativity and does 1 < 2 first to get a boolean, and then tries a true < 3 next, which subsequently fails of course.

Try out the other cases for yourself.

I reckon that when Mughal says "Relational operators are nonassociative." he means it mathematically speaking, and when he says "since relational operators have left associativity" he is refering to the Java compilation process.

Because the above example of 1 < 2 < 3 does not compile, this could be the justification of the use of the term "non-associative".
[ May 17, 2004: Message edited by: Barry Gaunt ]
 
meeta verma
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this out and u will find that the associativity is from left to right.

int i=1;
int j=i++ + i--;
System.out.println(j);

i=1;
j=i-- + i++;
System.out.println(j);

I am still finding out an example to show that != == also have associativity from left to right.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic