Win a copy of Mastering Corda: Blockchain for Java Developers this week in the Cloud/Virtualization forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Jj Roberts
  • Carey Brown
Bartenders:
  • salvin francis
  • Frits Walraven
  • Piet Souris

while and post increment

 
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please help me. I think the right answer is D as it is post-increment. But the right answer is B. Why???
What is the output of the following code:-
int x=4;
int y=7;
while(x++<5 && y++<8){
}
System.out.println("x=" +x +" y=" +y);
A. x=5 y=8
B. x=6 y=8
C. x=6 y=9
D. x=4 y=7
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
In the given code printing is done after the while loop.
Here is how it works:
1st iteration initial value x = 4, y = 7
x < 5 evalutes to true , x is incremented x = 5
second operand is evaluated
y<8 is true , y is incremented, y = 8
2nd iteration initial value x = 5, y = 8
x<5 evalutes to false, x is incremented x = 6
because the first operand is false , the second operand is NOT evaluated(short circuit). y is not incremented
while loop terminates.
Hence the output is x = 6, y = 8
-Vani
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Be careful! The println statement is not inside the while loop. Rethink the while statement being mindful of the logical && considerations and B is the correct answer.
 
antraarora
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Vani...that helps!!!
 
Hey, I'm supposed to be the guide! Wait up! No fair! You have the tiny ad!
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic