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.
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.