Skip to main content

ProwessApps

Learn · Practice · Excel

Write a program to demonstrate the difference between static and non-static variables.

Java Code Example — OOP Programs

ADVERTISEMENT

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

  1. Create a class Test.
  2. Declare an instance (non-static) variable a = 5.
  3. Declare a class (static) variable b = 5.
  4. Create a method display() that increments both a and b, then prints them.
  5. In main, create three separate Test objects one by one.
  6. 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 personal a starts 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 b in 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)
ADVERTISEMENT