This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes PLEASE REPLY ME Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "PLEASE REPLY ME" Watch "PLEASE REPLY ME" New topic
Author

PLEASE REPLY ME

Brijesh shah
Ranch Hand

Joined: Mar 16, 2007
Posts: 90
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

Joined: May 23, 2007
Posts: 1
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
Marshal

Joined: Mar 22, 2005
Posts: 41079
    
  43
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


Ping & DNS - my free Android networking tools app
Brijesh shah
Ranch Hand

Joined: Mar 16, 2007
Posts: 90
Thanks i got the answer...
[ May 25, 2007: Message edited by: brij. shah ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: PLEASE REPLY ME
 
Similar Threads
For loop running on Booleans
Class