public static void main () access non static variable

user1526671 picture user1526671 · Jul 17, 2012 · Viewed 48.2k times · Source

Its said that non-static variables cannot be used in a static method.But public static void main does.How is that?

Answer

Keppil picture Keppil · Jul 17, 2012

No, it doesn't.

public class A {
  int a = 2;
  public static void main(String[] args) {
    System.out.println(a); // won't compile!!
  }
}

but

public class A {
  static int a = 2;
  public static void main(String[] args) {
    System.out.println(a); // this works!
  }
}

or if you instantiate A

public class A {
  int a = 2;
  public static void main(String[] args) {
    A myA = new A();
    System.out.println(myA.a); // this works too!
  }
}

Also

public class A {
  public static void main(String[] args) {
    int a = 2;
    System.out.println(a); // this works too!
  }
}

will work, since a is a local variable here, and not an instance variable. A method local variable is always reachable during the execution of the method, regardless of if the method is static or not.