Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java declaring iterator outside for loop

Tags:

java

for-loop

According to the documentation of Oracle for loop is formed as we know it:

for (initialization; termination; increment) {
    statement(s)
}

E.g.,

class ForDemo {
    public static void main(String[] args){
         for(int i=1; i<11; i++){
              System.out.println("Count is: " + i);
         }
    }
}

Why can't we declare the initialization part outside the for loop like this?

 class ForDemo {
    public static void main(String[] args){
         int i = 1;
         for(i; i<11; i++){
              System.out.println("Count is: " + i);
         }
    }
}
like image 697
keser Avatar asked Oct 04 '18 18:10

keser


3 Answers

You can with:

 for(; i<11; i++){
      System.out.println("Count is: " + i);
 }

But the scope of i is different. i will now exist outside of the loop.

like image 151
JFPicard Avatar answered Nov 12 '22 22:11

JFPicard


You can. However you would simply have a blank ; in where the initialization usually goes:

int i = 1;
for(; i<11; i++){
    System.out.println("Count is: " + i);
}

The difference of this is that the scope of i is now broadened to outside of the loop. Which may be what you want. Otherwise it is best to keep variables to the tightest scope possible. As the docs for the for loop say:

declaring them within the initialization expression limits their life span and reduces errors.

Output:

Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
like image 29
GBlodgett Avatar answered Nov 12 '22 21:11

GBlodgett


What is really happening in the for loop that

BasicForStatement:
    for ( ForInit ; Expression; ForUpdate ) 

Initialization need a statment as the docs says

If the ForInit code is a list of statement expressions

From Java Docs

So in this code

 for(i; i<11; i++){ 
      System.out.println("Count is: " + i);
 }

i is not a statment, it is just a variable. So what is a statment?

Statements are roughly equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon (;).

Assignment expressions
Any use of ++ or --
Method invocations
Object creation expressions

Whit this knowlodge you can work any for loop if you know what is statemnt for example this for loop works

int i = 1; // Initializated
for(i++; i<11; i++){ // Whit a statemnt
    System.out.println("Count is: " + i);
}

and the output will be :

Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
like image 4
Gatusko Avatar answered Nov 12 '22 20:11

Gatusko