Java - Static Variables Explained with Example
In Java, Static variables means the memory is allocated statically and its life time is throughout the program execution time. In this example, counter is the static variable with in the function CountNumberOfTimes(). The variable counter is initialized with 0. The subsequent calls to this functions will not reassign the static variable to zero. The value printed on the screen would be 1, 2, 3, 4 and 5.
If you remove the static keyword for the counter variable, then you will see the program output as 1, 1, 1, 1 and 1. This explains the use and difference between a variable and static variable.
Source Code
import java.io.*;
class StaticVariable
{
public static void CountNumberOfTimes()
{
static int counter = 0;
counter++;
System.out.println(counter);
}
public static void main(String[] args)
{
System.out.println("\n\nProgram for explaining Static Variables Concept: \n");
for(int i = 0; i < 5; i++)
CountNumberOfTimes();
System.out.println("\n");
}
}Output
D:\Program Files\Java\jdk1.6.0_23\bin>javac StaticVariable.java
D:\Program Files\Java\jdk1.6.0_23\bin>java StaticVariable
Program for explaining Static Variables Concept:
1
2
3
4
5
|