ashni Prakash

Ranch Hand

Posts: 50

posted 9 years ago

public class Foozit {

public static void main(String[] args){

Integer x=0;

Integer y=0;

for(Short z=0;z<5;z++)

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

x++;

System.out.println(x+" "+y);

}

}

The above code is from K&B book

The correct answer to the above code is x=8,y=2.

Someone please help in understanding the logic.I am finding it confusing.

thanks

public class Foozit {

public static void main(String[] args){

Integer x=0;

Integer y=0;

for(Short z=0;z<5;z++)

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

x++;

System.out.println(x+" "+y);

}

}

The above code is from K&B book

The correct answer to the above code is x=8,y=2.

Someone please help in understanding the logic.I am finding it confusing.

thanks

Fu Dong Jia

Ranch Hand

Posts: 131

posted 9 years ago

hi!

below, show those variables changed process:

z ++x ++y x++

0 1 1 NOEXECUTE

1 2 2 NOEXECUTE

2 3 NOEXECUTE 4

3 5 NOEXECUTE 6

4 7 NOEXECUTE 8

Then,the finally value of x and y variables is 8 and 2

for "||" ,at runtime,if the left expression's value is true,the right expression will not execute,it's key of the problem.

below, show those variables changed process:

z ++x ++y x++

0 1 1 NOEXECUTE

1 2 2 NOEXECUTE

2 3 NOEXECUTE 4

3 5 NOEXECUTE 6

4 7 NOEXECUTE 8

Then,the finally value of x and y variables is 8 and 2

for "||" ,at runtime,if the left expression's value is true,the right expression will not execute,it's key of the problem.

who dare win!<br />SCJP5(94%)|SCWCD5(86%)|SCBCD(100%)|SCEA in progress

Fu Dong Jia

Ranch Hand

Posts: 131

posted 9 years ago

hi!

below, show those variables changed process:

z`````````++x`````````++y`````````x++

0``````````1```````````1`````````NOEXECUTE

1``````````2```````````2`````````NOEXECUTE

2``````````3```````NOEXECUTE```````4

3``````````5```````NOEXECUTE```````6

4``````````7```````NOEXECUTE```````8

Then,the finally value of x and y variables is 8 and 2

for "||" ,at runtime,if the left expression's value is true,the right expression will not execute,it's key of the problem.

below, show those variables changed process:

z`````````++x`````````++y`````````x++

0``````````1```````````1`````````NOEXECUTE

1``````````2```````````2`````````NOEXECUTE

2``````````3```````NOEXECUTE```````4

3``````````5```````NOEXECUTE```````6

4``````````7```````NOEXECUTE```````8

Then,the finally value of x and y variables is 8 and 2

for "||" ,at runtime,if the left expression's value is true,the right expression will not execute,it's key of the problem.

who dare win!<br />SCJP5(94%)|SCWCD5(86%)|SCBCD(100%)|SCEA in progress