Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

increment doubt

 
ashni Prakash
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Fu Dong Jia
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
ashni Prakash
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi jia,

Thanks for the explaination my doubt got cleared.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic