FOR LOOP CONFUSION

ben reitman

Total Post:96

Points:676
Posted by  ben reitman
Java  Loop 
 858  View(s)
Ratings:
Rate this:
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?

  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: For loop confusion

    In for loop init, you can declare multiple variables. In this case, both x and y are of type long. 
    In Java, you can't declare same variable name multiple times as either class field or local variable. 
    This explains why compiler complains when you declare variable x before for loop. 

    You can only have one field with a particular name. You can only have one local variable/parameter with a particular name in scope at any one time. 
    But you can have a local variable and a field with the same name and the local variable shadows the field

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!