Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java static variables and local variables [duplicate]

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 ?

like image 608
Gaurav Pathak Avatar asked Dec 23 '22 12:12

Gaurav Pathak


1 Answers

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.

like image 187
Joop Eggen Avatar answered Jan 02 '23 20:01

Joop Eggen