Its said that non-static variables cannot be used in a static method.But public static void main does.How is that?
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.