forum

Home / DeveloperSection / Forums / For loop confusion

For loop confusion

Anonymous User 1775 28-Apr-2015
I am utterly confused about something I read in the Oracle OCA book about for loops. One of the "special cases" of for loop where a variable is redeclared in the initialization block.
package food;
/**
 *
 * @author Calculus
 */
public class Food {
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
         
        //int x = 0;
        //long y = 10;
        for(long y = 0, x = 4; x < 5 && y< 10; x++, y++){
             
        } 
    }  
}

The code above builds successfully even though I have not given x a data type. To add to my confusion, if I attempt to remove the comment from int x = 0; then I incur the compiler's wrath. When I remove the comment from long y = 10; same result, except that part makes sense. 

I originally tested this code snippet from my book thinking it might be a typo. Sure enough, it doesn't compile. But it will if I remove long from y in the initialization block and declare it above the loop, then the compiler is happy

int x = 0;
        for(long y = 0, x = 4; x < 5 && y< 10; x++, y++){
             
        }

Can someone please straighten me out? Why does the top code compile without declaring x?


java java  loop 
Updated on 28-Apr-2015
I am a content writter !

Can you answer this question?


Answer

1 Answers

Liked By