Java: Static variables

This entry is part 35 of 54 in the series Learn Java

Static variables have the advantage that they persist throughout the life of the application.

They can therefore, for example, be used to record the number of times that a method has been called across all instances of the class.

The initial value for a static field will only be set once, sometime before the class or field is ever used.

package javaapplication26;

public class StaticMembers {

    static int count = 0;

    static void count() {
        count++;
    }

    void count1() {
        count++;
    }

    public static void main(String[] args) {       

        StaticMembers c = new StaticMembers();
        
        c.count1();
        count();
        c.count1();
        c.count1();
        count();
        
        System.out.println(count);
    }
}

staticvariables

Series Navigation<< Java: Advantage of static members
Java: Inheriting a class with members >>