aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes KB Question pg 314 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "KB Question pg 314" Watch "KB Question pg 314" New topic
Author

KB Question pg 314

Dinesh Tahiliani
Ranch Hand

Joined: Aug 06, 2007
Posts: 486


Can anyone explain me this code pleasee, not getting

Output is : 8,2


Thanks<br />Dinesh
Ireneusz Kordal
Ranch Hand

Joined: Jun 21, 2008
Posts: 423
In the expression a || b, first left side (a) is evaluated, and if it is 'true', then the right side is skipped, because for a || b, if only a=true then the whole expression is true.
Simillary for a && b, if a=false, then only only the left side (a) is evaluated (executed) and (b) is skipped.

This is not true for a | b and a & c expressions - in these cases compiler always evaluates boths sides (a and b).

So, look how the 'for' loop is executed:

1. z = 0, x = 0, y = 0
++x > 2 (x=1) --> false, ++y > 2 (y=1) -->false
2. z = 1, x = 1, y = 1
++x > 2 (x=2) --> false, ++y > 2 (y=2) -->false
3. z = 2, x = 2, y = 2
++x > 2 (x=3) --> true!! - so don't evaluate ++y > 2 (y=2)!!
whole if condition is true --> execute x++ (x=4)
4. z = 3, x = 4, y = 2
the same as point 3 - x is incremented twice, and y is unchanged
5. z = 4, x = 6, y = 2
the same as in 3 - x is incremented twice, and y is unchanged

in the end, z=5, x=8 and y=2
[ June 23, 2008: Message edited by: Ireneusz Kordal ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: KB Question pg 314