Home > DeveloperSection > Forums > For loop confusion
ben reitman
ben reitman

Total Post:96

Posted on    April-28-2015 12:42 AM

 Java Java  Loop 

 1 Reply(s)
 780  View(s)
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?

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    April-28-2015 7:25 AM

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

Don't want to miss updates? Please click the below button!

Follow MindStick