I am new in Java and came across one OCJA-1.8 sample question where I am having some doubt. I need clarification on this behavior of JVM.
 public class Test{
static int x=1;//**This is static class level variable**
   public static void main(String[] args){
    int[] nums={1,2,3,4,5};
    for(int x:nums){ // Local variable declared for for-each loop.
        System.out.println(x);
    }
  }
}
Why the JVM have not thrown the error as duplicate variable, For the variable which is declared inside for each loop 'int x'. As static variable has class level scope ?
The local variable hides the original static field somewhat, but it is not inaccessible:
Test.x
And for non-static fields:
this.x // not in this case
So it is allowed, and in effect one often sees:
public class Pt {
    private final int x;
    public Pt(int x) {
        this.x = x;
    }
}
Which prevents the need to introduce some convention (_x, mX).
What is not allowed:
void f() {
    int x = 42;
    if (true) {
        int x = 13; // COMPILER ERROR
        ...
    }
}
As this is bad style, causing confusion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With