jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Help" Watch "Help" New topic


prerna boja
Ranch Hand

Joined: Aug 19, 2004
Posts: 67
Hi all,

Please explain me the following code.

class test
static int m1(String s, int i)
System.out.print(s + i);
return i;
public static void main (String[] args)
int j = 0;
for (int i = m1("A",0); m1("B",i) < 2; m1("C",++i))
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
Here is your code properly formatted with code tags.

Now, what is your question?

If you want to know the output, run it yourself and see.

Mike Gershman
SCJP 1.4, SCWCD in process
Igor Stojanovic
Ranch Hand

Joined: Feb 18, 2005
Posts: 58

The for statement executes some initialization code, then executes an Expression, a Statement, and some update code repeatedly until the value of the Expression is false.

for ( ForInit ; Expression ; ForUpdate )

A for statement is executed by first executing the ForInit code;next, a for iteration step is performed,If the Expression is present, it is evaluated then the contained Statement is executed.If execution of the Statement completes normally then the ForUpdate part is evaluated in sequence from left to right...

So,in your example we have this parts of code:

ForInit>>>>> int i = m1("A",0)
Expression>> m1("B",i) < 2
ForUpdate>>> m1("C",++i)
Statement>>> m1("J",++j)

First program executes "ForInit" and we get output : A0
Second program executes "Expression" and we get output : B0
Third program executes "Statement" and we get output : J1
4th "ForUpdate" : C1
5th "Expression" : B1
6th "Statement" : J2
7th "ForUpdate" : C2
8th "Expression" : B2

since out last expression didnt pass equality test for loop ends.

I hope this helps you For more info checkJava Language Specification

P.S. Here is your example written using while loop,it might be easier for you to understand:

I think that is the way how "for loop" get's internally translated to "while loop" in C language.

kind regards

[ February 21, 2005: Message edited by: Igor Stojanovic ]

[ February 21, 2005: Message edited by: Igor Stojanovic ]
[ February 21, 2005: Message edited by: Igor Stojanovic ]
I agree. Here's the link: http://aspose.com/file-tools
subject: Help
It's not a secret anymore!