Write A Program In Java To Demonstrate The Use Of “static” Keyword.
In this program, we will create a java program to demonstrate the use of “static” keyword.
Before demonstrate the program we will understand the use of "static" keyword.
he `static` keyword in Java is mainly used for memory management. It can be used with variables, methods, blocks and nested classes¹. The `static` keyword belongs to the class rather than an instance of the class¹.
A `static` variable can be used to refer to a common property of all objects (which is not unique for each object). The `static` variable gets memory only once in the class area at the time of class loading¹.
A `static` method can be accessed without creating an object of a class⁴. This means that you can call a `static` method directly on a class, rather than on an instance of that class.
public class StaticExample { // static variable static int count = 0;
// instance variable int instanceCount = 0;
// constructor public StaticExample() { count++; instanceCount++; }
public static void main(String[] args) { StaticExample obj1 = new StaticExample(); System.out.println("obj1: count is " + obj1.count + ", instanceCount is " + obj1.instanceCount);
StaticExample obj2 = new StaticExample(); System.out.println("obj2: count is " + obj2.count + ", instanceCount is " + obj2.instanceCount); }}
obj1: count is 1, instanceCount is 1
obj2: count is 2, instanceCount is 1
In this example, we have a static variable count and an instance variable instanceCount. The static variable belongs to the class and is shared by all instances of the class. The instance variable belongs to each individual object and is not shared.
When we create two objects of the StaticExample class, we can see that the count variable is incremented twice (once for each object), while the instanceCount variable is only incremented once for each object.