![]() |
![]() |
Java Interface | |
Java Class vs Interface | |
Java Multiple Inheritance | |
Java Nested Interface |
Java Packages | |
Java Built in packages | |
Java Package Access Specifiers |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions |
Static keyword is used to make static members. The static members are associated with class itself rather than individual objects. They are also referred as class variables and class methods.
Normally the class contains two sections as
They are called as instances of class because every time when object is created then a new copy of variables and methods are created which are accessed using . operator.
When we want to define members which are common to all objects and access without using . operator then that members belongs to the class rather than objects.
Syntax
class ClassName { static int varName; // static field declaration static returnType methodName(parameters list); // static method declaration }
The public static void main() method inside class is also a static method in java. It is called without creating an object of that class.
Example - without using static variable
class WithoutStatic { int counter = 0; WithoutStatic() { counter ++; show(); } void show() { System.out.println("Counter = "+counter); } public static void main(String args[]) { WithoutStatic n1,n2,n3,n4,n5; n1 = new WithoutStatic(); n2 = new WithoutStatic(); n3 = new WithoutStatic(); n4 = new WithoutStatic(); n5 = new WithoutStatic(); } }
Output
In above example we have created 5 objects of WithoutStatic class. Every time default constructor is called then counter is incremented from 0 to 1 but, the incremented value is not shared to all objects hence every objects gets the value 1.
Example - Using static variable
class UsingStatic { static int counter; // auto initialized to zero UsingStatic() { counter ++; show(); } void show() { System.out.println("Counter = "+counter); } public static void main(String args[]) { UsingStatic n1,n2,n3,n4,n5; n1 = new UsingStatic(); n2 = new UsingStatic(); n3 = new UsingStatic(); n4 = new UsingStatic(); n5 = new UsingStatic(); } }
Output
In above example we have declared counter variable as static.When first object is created then it is automatically initialized to zero. The default constructor increments the value of counter by 1 and immediately shares to all objects.The new objects starts to increments counter from previous value.