Is t1
static or non-static?
class Test {
void display() {
System.out.println("hello");
}
public static void main(String a[]) {
Test t1 = new Test(); //object created
t1.display();
}
}
Is t1
static or non-static?
class Test {
void display() {
System.out.println("hello");
}
public static void main(String a[]) {
Test t1 = new Test(); //object created
t1.display();
}
}
t1
is a local variable and local variables are not static since they live in the scope of the method while a static variable/field exists independently of the method execution.
A static variable/field must be declared outside methods.
It is not itself static, though it exists solely within a static context. The static
descriptor only applies to class-level entities. Consider this class (a simplified version of the built in java.lang.Math class):
class EasyMath {
public static final double PI = 3.17;
public static int quadruple(int i) {
int num = i * 4;
return num;
}
}
You would reference the value of PI
directly, using EasyMath.PI
. It's a class variable. It belongs directly to the EasyMath
class, not to instances of the class.
Likewise, you would reference the quadruple
method from the class as well: EasyMath.quadruple(6)
. That's because the method is static, it belongs directly to the class.
Note that the quadruple
method defined a local variable named num
. However, you're not able to reference that using EasyMath.num
. It does not belong to the class.
It's scoped locally to the static quadruple
method, so it's available for use only in that method, and nowhere else. Another static method would not be able to see it or reference it. Likewise, if there were any instance methods, they would not be able to see it either. A local variable can never be static.