Java Global Variable: Declaration & Examples
Unlike C/C++, there is not a true global variable in Java. However, we can get close. This lesson will show you how to declare semi-global variables in Java using working code examples.
Global Variables
If you have experience with other programming languages, such as C and C++, you have probably used global variables. A global variable is one that is accessible to all parts of a program and is usually declared as part of the first lines of code.
Java doesn’t technically support global variables. As a pure object-oriented language, everything needs to be part of a class. The reason is to protect data and members of classes from being changed, inadvertently or on purpose, by other parts of the program. However, you still may need to have variables that can be accessed across your program, and not confined to specific classes.
Let’s take a look at some ways to achieve this, starting with static variables.
Static Variables
Because Java is object-oriented, all variables are members of classes. However, we can create static variables that are more accessible. The static modifier tells Java that the variable can be used across all instances of the class. Therefore, if you create a variable for pay rate and make it static, any instance of the parent class can access pay rate.
This code shows how we declare two variables within a class. Although we’re declaring price and pages in the Openclass class, they are static variables and can now be used by instances of Openclass.
public class Openclass {
public static double price = 15.24;
public static long pages = 1053;
}
In another class, we can get to those variables by simply denoting the class, putting in a period, and finally the field name. The following code creates new variables but assigns the value of the global variables to these new variables:
public static void main(String[] args) {
double newPrice = Openclass.price;
long newPages = Openclass.pages;
System.out.println(newPrice);
System.out.println(newPages);
}
When this program runs, we get this output:
Java global methods output
You can now see that the traditional global variable doesn’t exist in Java. Yes, we technically have variables available across the program, but we also created additional variables to hold the values of these static variables.
However, there is another way to create a somewhat global variable. We’ll discuss that next.