0

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();
    } 
}
nbrooks
  • 18,126
  • 5
  • 54
  • 66

2 Answers2

0

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.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
-1

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.

nbrooks
  • 18,126
  • 5
  • 54
  • 66
  • It exists only within a method-local context. – user207421 Oct 22 '16 at 09:39
  • @EJP The context is still static, it's just the variable's scope that's local. If you were to try to access an instance variable from within that method, for example, Java would complain about accessing a non-static variable from a *static context*. Within the `main` method the context is static. – nbrooks Oct 22 '16 at 09:46