Syntax of Static Variable
static type varName = value;
type is any data type in java.
varName is any valid identifier in java. It is a variable name.
value is an optional. You can initialize variable by assigning its value.
Example of Static Variable
Example 1 : Program that illustrates static variable use in java
class Employee
public class StaticVariable
{
static int noOfObjects = 0;
StaticVariable()
{
noOfObjects++;
}
public static void main(String[] args)
{
StaticVariable sObj1 = new StaticVariable();
System.out.println("Number of objects for sObj1 : " + sObj1.noOfObjects);
StaticVariable sObj2 = new StaticVariable();
System.out.println("");
System.out.println("Number of objects for sObj1 : " + sObj1.noOfObjects);
System.out.println("Number of objects for sObj2 : " + sObj2.noOfObjects);
StaticVariable sv3 = new StaticVariable();
System.out.println("");
System.out.println("Number of objects for sObj1 : " + sObj1.noOfObjects);
System.out.println("Number of objects for sObj2 : " + sObj2.noOfObjects);
System.out.println("Number of objects for sObj3 : " + sObj3.noOfObjects);
}
}
Output
Number of objects for sObj1 : 1
Number of objects for sObj1 : 2
Number of objects for sObj2 : 2
Number of objects for sObj1 : 3
Number of objects for sObj2 : 3
Number of objects for sObj3 : 3
As you can note that noOfObjects variable is shared among all objects of class StaticVariable.