Class Variables

A class variable is a variable that any method in a class can access, including static methods, such as main. When declaring a class variable, you have two basic rules to follow:

check.png You must place the declaration within the body of the class but not within any of the class methods.

check.png You must include the word static in the declaration. The word static comes before the variable type.

The following program shows the proper way to declare a class variable named helloMessage:

public class HelloApp

{

static String helloMessage;

public static void main(String[] args)

{

helloMessage = “Hello, World!”;

System.out.println(helloMessage);

}

}

The declaration includes static and is placed within the HelloApp class body but not within the body of the main method.

tip.eps Although it is common to place class variable declarations at the beginning of a class, that’s not a requirement. You can place class variable declarations anywhere within a class, but lumping them all together at the beginning of the class makes them easier to find.

Get Java For Dummies Quick Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.