• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Help

 
prerna boja
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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))
{
m1("J",++j);
}
}}
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Igor Stojanovic
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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.

ForStatement:
for ( ForInit ; Expression ; ForUpdate )
Statement

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
Igor

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

[ February 21, 2005: Message edited by: Igor Stojanovic ]
[ February 21, 2005: Message edited by: Igor Stojanovic ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic