• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Tim Cooke
Sheriffs:
  • Rob Spoor
  • Liutauras Vilda
  • paul wheaton
Saloon Keepers:
  • Tim Holloway
  • Tim Moores
  • Mikalai Zaikin
  • Carey Brown
  • Piet Souris
Bartenders:
  • Stephan van Hulst

increment doubt

 
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi jia,

Thanks for the explaination my doubt got cleared.
 
We cannot change unless we survive, but we will not survive unless we change. Evolving tiny ad:
Gift giving made easy with the permaculture playing cards
https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
reply
    Bookmark Topic Watch Topic
  • New Topic