• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

PLEASE REPLY ME

 
Brijesh shah
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear All;

Can anyone please explain me how this code works...The following codes output is A B D C B D C B ....I dont understand how itx executed..
public class Delta{
static boolean foo(char c){
System.out.print(c+" ");
return true;
}
public static void main(String args[]){
int i = 0;
for(foo('A'); foo('B')&&i<2; foo('C')){
i++;
foo('D');
}
}
}

Thanking you in advance;

Best Regards

Brijesh Shah
[ May 25, 2007: Message edited by: brij. shah ]
 
Jason Tovey
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
foo(char c) prints out the character it receives and then returns true. When the for loop is initialized, foo('A') is called. This prints out the 'A' that you see. Then the test condition is evaluated -- foo('B') && i<2 -- foo('B') prints out the 'B'. On the first iteration, i=0 so the compound expression is true and the body of the for loop is executed: i is incremented and foo('D') is run, which prints out 'D'. Then the 'increment' portion of the for loop is run, which is foo('C') -- this prints out C.
Output so far: A B D C
Then the test condition is evaluated again. foo('B') prints out 'B' and returns true, and i is still less than 2, as it is now 1. Thus the body is executed and i becomes 2 and 'D' is output. The 'increment' portion is run again and 'C' is output.
Output so far: A B D C B D C
Finally the test condition is evaluated again, which prints out 'B'. So foo('B') returns true, but !(i<2) so the loop terminates.
Final Output: A B D C B D C B
 
Ulf Dittmer
Rancher
Posts: 42968
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It may be easier to understand if you work your way backwards. Look at the output, and then that ask yourself "which code MUST have been executed" in order to get this output. You need to be familiar with how the for loop works, though.

And for future reference: UseAMeaningfulSubjectLine
 
Brijesh shah
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks i got the answer...
[ May 25, 2007: Message edited by: brij. shah ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic