Search code examples
javaloopsfinalaccess-modifiers

Why Java will not allow to use access modifiers in loops?


for(public int i=0;i<10;i++) {

        System.out.println(i);

        }
for(private int i=0;i<10;i++) {

        System.out.println(i);

    }

Eclipse says only final is permitted.


Solution

  • Firstly we need to know that what is the need of Access modifiers. An access modifier restricts the access of a class, constructor, data member and method in another class.

    But when we declare a variable or anything inside a loop their scope/use is restricted only to that loop. That means we can use these variables only inside that loop. We can't use these variables outside of that loop. (SUN people who wrote java have restricted it).

    so if we don't use loop variables outside of loop then what is the need to use Access modifiers inside loop. That's why java doesn't allow it.