You are on page 1of 2

STATIC METHODS AND VARIABLES

Static Methods:
Methods in Java can be either Static or non-static. The non-static methods are called
Instance Methods.
Instance methods are associated with an object and use instance variables of that object.
If you have a class and it has methods that are not preceded by the keyword ‘static’, the
are called instance methods.

Example:

Class Test {
Instance variable/
int a; Non-static variable

Static variable
static int b;
Instance Method/Non-
void normalMethod() { }
static method

static void myStaticMethod() { a = 4; }


Static Method
}

public class mainClass {

public static void main(String[] args)


{

Test tobj = new Test(); Creating an Instance of class Test. An


object ‘tobj’ is created.

System.out.println(Test.b);

tobj.a = 5;
Access instance variable
System.out.println(tobj.a); using the object ‘tobj’

Call static methods


Test.myStaticMethod(); using class name
tobj.normalMethod(); Call Instance method using
} Object ‘tobj’.
}

• A static variable is called a “Class variable”.

• A static variable/class variable can be accessed directly w/o the need to create
an instance.
Example: In the above program, the static variable ‘b’ can be accessed by the
statement
System.out.println(Test.b);
Here ‘Test’ is the class within which the variable ‘b’ resides.

• Static methods use no instance variables of any object of the class they are
defined in.
Example: In the above program for the static method ‘mystaticMethod()’, the
variable ‘a’ cannot be used in the body of the method, as ‘a’ is an instance
variable. We see an error saying ‘non-static variable cannot be referenced from
static context’. Static variables can be used with static methods.
• Instance variables can be accessed only by instance methods.
• Static methods are called using class name if doing from other classes.
• Instance methods are called using instance of that class.

You might also like