• Post Reply Bookmark Topic Watch Topic
  • New Topic

about for loop in Java  RSS feed

 
Ranch Hand
Posts: 46
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey guys, when I try to run the code below

the output is:
0 0

Can anyone explain to me why?
 
Greenhorn
Posts: 15
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you never enter into the loop.

the condition of your loop is j < i (0 < 0), it returns false right away.

The output that you see is from the the System.out after the loop.

D.
 
Duc Ta
Ranch Hand
Posts: 46
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
D Nobels wrote:you never enter into the loop.

the condition of your loop is j < i (0 < 0), it returns false right away.

The output that you see is from the the System.out after the loop.

D.

I know it, but if I never enter into the loop it mean that the method variables i and j is never initialized. It mean that there will compile error because the value of method variables must be initialized before they are used, but there is no error the code compile normally. This is my confusing part.
 
Saloon Keeper
Posts: 3330
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The for() loop contains three sections:
for( <initialization> ; <while-expression> ; <post-loop> )
The "initialization" ALWAYS takes place.

The body of the loop is only entered if the "while-expression" is true.
 
D Nobels
Greenhorn
Posts: 15
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Duc Ta wrote:
I know it, but if I never enter into the loop it mean that the method variables i and j is never initialized. It mean that there will compile error because the value of method variables must be initialized before they are used, but there is no error the code compile normally. This is my confusing part.


What I mean by it will not enter the loop is that it will not enter the loop block.
Before the first iteration, the variables are still initialized and the control condition evaluated.
 
Carey Brown
Saloon Keeper
Posts: 3330
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Duc Ta wrote:... if I never enter into the loop it mean that the method variables i and j is never initialized.

This is not true.

And I assume you mean "never enter the body of the loop".
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!