File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Associativity(Left or Right) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Associativity(Left or Right)" Watch "Associativity(Left or Right)" New topic

Associativity(Left or Right)

Swamy Nathan
Ranch Hand

Joined: May 16, 2004
Posts: 187
Hello there!
What is the associativity of expr++ and expr--?
Also what is the associativity of == and !=?
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Here's a table of java operations that will help you.

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
Sandeep Advani
Ranch Hand

Joined: Mar 11, 2004
Posts: 78
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.

Swamy Nathan
Ranch Hand

Joined: May 16, 2004
Posts: 187
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

Joined: Aug 03, 2002
Posts: 7729
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

Joined: May 15, 2004
Posts: 19
Try this out and u will find that the associativity is from left to right.

int i=1;
int j=i++ + i--;

j=i-- + i++;

I am still finding out an example to show that != == also have associativity from left to right.
I agree. Here's the link:
subject: Associativity(Left or Right)