Programming & Scripting Tutorials

Java: Static Variables



When objects are created from the same class, each one has its own copy of class variables. But this is not the case when it is declared as static.
To declare a static variable you simply use the static keyword like so:

static int StatIntOne = 1;


To see these in action read through this program:

class Party{
    private String firstname;
    private String lastname;
    private static int peopleatparty = 0;
    Party(String first, String last){
    firstname = first;
    lastname = last;
    peopleatparty++;
    System.out.printf("Welcome to the party %s %s,\nPeople: %d.\n\n", firstname, lastname, peopleatparty);
    }

};

public class Main {

    public static void main(String[] args) {

     Party Person1 = new Party("Bob", "Smith");
     Party Person2 = new Party("Fred", "Savage");
     Party Person3 = new Party("Jill", "Hill");

    }

}

All this does is share the variable peopleatparty between all the objects so that we can easily track how many people are there without difficulty.
Statics are extremely important in java and are very very useful, now you know them you will constantly use them.


This Java tutorial was written by


Back to Java

Advertisement: