Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static method in java

Tags:

java

static

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

like image 455
sandhya Avatar asked Mar 06 '10 09:03

sandhya


1 Answers

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?
    }
}
like image 156
Mihir Mathuria Avatar answered Oct 10 '22 00:10

Mihir Mathuria