Static variables are declared using static modifier. These variables doesn't belong to any particular object, they belong to class and can be accessed by just using the class name. These variables are common to their class objects. below is a tiny example of static variable usage in java.
public class DemoStaticVar {
static int STVAL = 300;
static
{
STVAL = 400;
}
public static void main(String args[])
{
System.out.printf("Class variable STVAL's value is %d",DemoStaticVar.STVAL);
}
}
In this code two types of static variable initializations are present. First one when declaring the static variable STVAL, second int the static block. The value of the STVAL depends on the order of the declaration statement and static block. The one which comes last overrides the value of the static variable. Also observe that static variable is accessed using class name like this DemoStaticVar.STVAL. In this code we can see c-style print statement with string formatitting.
Output of the above code is
Class variable STVAL's value is 400
Let's see by exchanging the order of the statements.
public class DemoStaticVar {
static
{
STVAL = 400;
}
static int STVAL = 300;
public static void main(String args[])
{
System.out.printf("Class variable STVAL's value is %d",DemoStaticVar.STVAL);
}
}
Now the output will be
Class variable STVAL's value is 300