programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

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

agustino felisberto
Greenhorn
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
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
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
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
Posts: 6
now i fully understand.thanks

 It is sorta covered in the JavaRanch Style Guide.