wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Expression evaluation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Expression evaluation" Watch "Expression evaluation" New topic
Author

Expression evaluation

Philip Pomario
Ranch Hand

Joined: Oct 03, 2003
Posts: 113
Could someone please explain me the order of evaluation the following expression uses to execute? I guess it would be easier just to put the extra parenthesis in place.

int i=1;
int j = 2;
if (i==1 || j==2){
System.out.println("true");
}

Thanks!
Paul Santa Maria
Ranch Hand

Joined: Feb 24, 2004
Posts: 236
Hi -

A quick Google search for "Java operator precedence" took me straight to Sun's official documentation:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/expressions.html

You'll note in the table that "equality" (==, !=) has higher precedence than "logical OR". So the expression will be evaluated:

(i == 1) || (j == 2 )
<= THIS WILL, OF COURSE, EVALUATE TO "TRUE"

One thing the Java page *doesn't* mention is that "&&" and "||" are "short circuit" operators - that is, the second expression will *not* be evaluated if the first one is true. This can often be a very important distinction.
Hope that helps .. PSM
[ February 11, 2005: Message edited by: Paul Santa Maria ]

Paul M. Santa Maria, SCJP
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Filipe Pomar:
I guess it would be easier just to put the extra parenthesis in place.


Yes, I'd probably do exactly that.


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Philip Pomario
Ranch Hand

Joined: Oct 03, 2003
Posts: 113
Thanks guys!
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Originally posted by Paul Santa Maria:

...
One thing the Java page *doesn't* mention is that "&&" and "||" are "short circuit" operators - that is, the second expression will *not* be evaluated if the first one is true. This can often be a very important distinction.
Hope that helps .. PSM

[ February 11, 2005: Message edited by: Paul Santa Maria ]

This statement is only true of the || operator. For the && operator, if the first operand evaluates to false, then the second expression is not evaluated.


Java API Documentation
The Java Tutorial
Philip Pomario
Ranch Hand

Joined: Oct 03, 2003
Posts: 113
I just passed the SCJP1.4 exam and wanted to post this appreciation note to thank everyone who helped me understand Java a little better. Without your help this personal achievement wouldn't be possible.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Expression evaluation