‹‹ Previous
Next ››
Java Static Variable
- Static variable is used to retain its value on every function call.
- Static variable is initialized once.
- Scope of static variable is at program level.
- If no initial value is given to static variable, then its default value is zero.
- Static variable is defined using the keyword 'static'.
Example
class countobject {
static int i; // default value of i is zero
countobject ()
{
i++;
}
void show()
{
System.out.println("Number of objects are " + i);
}
public static void main(String args[])
{
countobject obj1 = new countobject();
countobject obj2 = new countobject();
countobject obj3 = new countobject();
obj3.show();
}
}
Explanation of the program
- Class countobject defines a static variable i . It is of type integer.
- Here, no initial value is given to static variable i . Therefore, default value of i is zero.
- A constructor is defined in which static variable i is incremented whenever an object of the class countobject is created.
- Three objects are created in the example.
- To display value of static variable i . We call show() method.
- Because variable i is defined as static. Therefore, variable i retains its value in multiple calls of the constructor.
Output of the program
Number of objects are 3
‹‹ Previous
Next ››