File APIs for Java Developers Manipulate DOC, XLS, PPT, PDF and many others from your application. http://aspose.com/file-tools
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login

# i don't get it!.please somebody help me.

agustino felisberto
Greenhorn

Joined: Oct 16, 2007
Posts: 6
why this code have this result 8 2:

class Foozit {
public static void main(string[] arg {
Integer x = 0;
Integer y = 0;
for(Short z = 0;z < 5;z++)
if((++x> 2)|| (++y >2));
x++;
system.out.println(x + " " + y);

}
}
what was done?
can somebody explain me why the result is 8 2
the iteration loop?what was done?
Tony Smith
Ranch Hand

Joined: Jul 07, 2007
Posts: 229
I haven't gone through it in detail, but take a look at :

if((++x> 2)|| (++y >2));

notice the || short-cut OR operator? that means if the left side is true, right side is never evaluated. So when ++x>2, it will never go to ++y>2 part, so that kind of explain why y is ended up with just 2. So go over the code few times and write in paper and see what happens.
agustino felisberto
Greenhorn

Joined: Oct 16, 2007
Posts: 6
yeah.this where is exactly my problem the left side.the right side i fully understand. why the left side stops at 8?

lets see x=0 y=0;
x=1 y=1;
x=2 y=2;
x=3 if((++x>2)|| {++y >2)) true. i think it stops there with the third iteration of the loop,y is never touched again.

my question is why x==8 at end?not 10 or 12?or even x==3 and y==2?this exercice is in the book scjp(kathy sierra& bert bates).
ronnir paterl
Greenhorn

Joined: Oct 18, 2007
Posts: 11
its pretty simple...

Consider the outermost for loop

for z=2 x reaches 3

now apply x++ (because "if" condition is evaluated to be true by Short circuit evaluation)

so at this point z=2, x=4 and y=2

similarly when z=3, x=6 and y=2

and finally z=4, x=8 and y=2

the basic idea is once z reaches 2, x increments twice (++x and x++) for every value of z
agustino felisberto
Greenhorn

Joined: Oct 16, 2007
Posts: 6
now i fully understand.thanks

Consider Paul's rocket mass heater.

subject: i don't get it!.please somebody help me.