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:
You must place the declaration within the body of the class but not within any of the class methods.
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.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access