Write a program to demonstrate the difference between static and non-static variables.
Objective
Write a Java program to clearly demonstrate the difference between static and non-static variables.
Algorithm / Approach
- Create a class
Test. - Declare an instance (non-static) variable
a = 5. - Declare a class (static) variable
b = 5. - Create a method
display()that increments bothaandb, then prints them. - In
main, create three separateTestobjects one by one. - Call
display()on each object sequentially.
Test.java
class Test {
int a = 5;
static int b = 5;
void display() {
a++;
b++;
System.out.println("A = "+a);
System.out.println("B = "+b);
}
public static void main(String[] a)
{
Test t = new Test();
t.display();
Test t2 = new Test();
t2.display();
Test t3 = new Test();
t3.display();
}
}
Expected Output
A = 6 B = 6 A = 6 B = 7 A = 6 B = 8
Explanation of the Program
- When you run this program,
a(non-static) prints as 6 every time. This is because every object gets its own fresh copy of instance variables. When a new object is created, its personalastarts at 5 and increments to 6. - However,
b(static) prints as 6, then 7, then 8. This is because static variables are shared across ALL objects of the class. - There is only one single copy of
bin memory. When the first object increments it to 6, the second object sees 6 and increments it to 7.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)