Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

flow _Control _Please rectify me if wrong..

 
deepu Bhalotia
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class JMM118
{
public static void main (String[] args)
{
int i = 0, j = 9;
while (i++ <= j--)
{
i++; //i=5, j=4
if (j < 5)
break;
}
System.out.print(i + "," + j);
}
}

I think the Answer for this Flow is 8,5. But in http://www.danchisholm.net/july21/mybook/chapter8/exam1ans.html
They have given the Answer as 9,4.

Can anybody please Verify me...

Thanks in Advance

Deepak
 
Stefan Willi
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The state of the variables after the last loop in the while are:
i = 8
j = 5
Now the condition i <= j = false.
But the post ++ and -- operator increment and decrement the variables after evaluating the condition (i++ <= j--). The new values are i = 9 and j = 4

Stefan
 
Timmy Marks
Ranch Hand
Posts: 226
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


The comp and val represent values used for comparison and the value of the variable at the end of the line. Flow is as follows:




Line 3 never evaluates as true, because in the iteration where j becomes less than 5, it is also < i.

Does this make sense?
 
deepu Bhalotia
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Timmy...

in last condition i didn't increment the i and decrement J. Thats why i was getting 8,5.
 
deepak khiyani
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi deepu,
i have modified your code a little bit.....please check this whether it helps.....

class Test
{
public static void main (String[] args)
{
int i = 0, j = 9;
while (i++ <= j--)
{
i++; //i=5, j=4
if (j < 5)
break;
System.out.println(i + "," + j);
}
//System.out.print(i + "," + j);
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic