sandhya sandhya - 6 months ago 34
Java Question

Static method in java

I heard that static methods should use only static variables in java.
But, main method is also static, right?


Your question: is the statement " static methods should use only static variables" correct?

No. The statement is not correct.

The correct statement will be "static methods can only use those instance variables that are defined static"

Take a look at following code and read the comments:

Class A{
    int i;
    static int j;

    public static void methodA(){
        i = 5; //cannot use since i is not static
        j = 2; //can use.

        int k = 3; //k is local variable and can be used no problem

        **EDIT:**//if you want to access i
        A a = new A();
        //A.i = 5; //can use.  
        a.i = 5; // it should be non-capital "a" right?