Previous | Next | Trail Map | Writing Java Programs | The Anatomy of a Java Application

Static vs. Instance

import java.util.Date;
class DateApp {
    public static void main(String args[]) {
        Date today = new Date();
The last line of the main() method uses the System class from the java.lang package to display the current date and time. First, let's break down the line of code that invokes the println method, then look at the details of the argument passed to it.

Static Methods and Variables

In the Java statement
System.out refers to the out variable of the System class. As you can see, to refer an class's static variables and methods, you use a syntax similar to the C and C++ syntax for obtaining the elements in a structure. You join the class's name and the name of the static method or static variable together with a period ('.').

Notice that the application never instantiated the System class and that out is referred to directly from the class. This is because out is declared as a static variable--a variable associated with the class rather than with an instance of the class. You can also associate methods with a class--static methods-- using static.

Instance Methods and Variables

Methods and variables that are not declared as static are known as instance methods and instance variables. To refer to instance methods and variables, you must instantiate the class first, then obtain the methods and variables from the instance.

System's out variable is an object, an instance of the PrintStream class (from the package), that implements the standard output stream. The Standard Output Stream in The Nuts and Bolts of the Java Language discusses the standard output stream in detail. For now, just think of it as a convenient place for an application to display its results.

System creates out, and all of its other static variables, when the System class is loaded into the application. The next part of the Java statement calls one of out's instance methods: println().


As you see, you refer to an object's instance methods and variables similar to the way you refer a class's static methods and variables. You join the object's name and the name of the instance method or instance variable together with a period ('.').

The Java compiler allows you to cascade these references to static and instance methods and variables together and use the construct that appears in the listing above


Sum it Up

Static variables and methods are also known as class variables or class methods because each class variable and each class method occurs once per class. Instance methods and variables occur once per instance of a class.

Previous | Next | Trail Map | Writing Java Programs | The Anatomy of a Java Application