• Post Reply Bookmark Topic Watch Topic
  • New Topic

Operators precedence  RSS feed

 
Golla Vensiri
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ,

Am very week in operator precedence
Can any one give clear explanation which operator should be considered first??

int a1=1;
System.out.println(4 == 2 && ++a1 < 4 );

What i think is
1. as prefix ++ operator has more precedence ++a1 shouild be evaluated
2. ++a1 < 4 should be evaluated
so on

But it first check for 4==2 and the next is not executed as it evalutaes to false

Can you please help me from this confusion
 
Norm Radder
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Its usually best to put ALL expressions in parans rather than trust to memory about operator precedence.

Using compiler shortcuts leads to problems!! Code it correctly from the start.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Norm. Why would you write code like this in a realy program? you should use parentheses to clarify operator precedence and so that it works the way you expect.

However, even if you add parens, there is another issue that you seem to have missed. First of all, I think the < and == operators have equal precedence. This means that the left-most is evaluated first. Note that 4==2 evaluates to false. You probably expect that < will be evaluated next. However, the && operator fits in a group called "short-circuit operators". Because the left side of the && operator evaluates to false, we already know that the complete expression will be false without evaluating the right side. Java is smart enough to know this, too, so it "short-circuits" the operation and doesn't waste any time evaluating the right side of the expression.

As a side note, the || operator works similarly. The difference is that if the left side evaluates to true then it doesn't bother evaluating the right side.

HTH

Layne
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Layne is correct. It will never evaluate the right side of an && if the left side is false. That is important in cases like

a != null && b != null && a.equals(b)

I keep a book with a tab on the precedence page on my desk as I just can't remember. But it often encourages me to forgo the parenthesis. Then when the book isisnt around and I am debugging I end up adding them anyway :roll:
[ September 20, 2005: Message edited by: Mr. C Lamont Gilbert ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!