Have you ever wished an easy-to-use global keyword existed to create a global variable in Java? As it turns out, the concept of a global variable in Java is not as straightforward as in some other programming languages due to Java’s object-oriented nature. However, you can achieve similar functionality using class-level variables. This article will guide you through understanding different types of variables in Java and how to create a global variable using static variables.
Table of contents
- Global variables
- Local variables
- Static variables
- Instance variables
- How to create a global variable
- Default values
- Conclusion
Key takeaway
In Java, you can create global variables by using static fields, which belong to the class and can be accessed from anywhere in the program using the class name. Static fields ensure that the variable is shared across all instances of that class.
What is a global variable?
As the name implies, a global variable is a variable that is accessible from any part of the program. In languages like C or C++, global variables are declared outside of all functions, making them accessible from any function within the program.
However, you may be surprised to learn that Java does not have true global variables. That does not mean you can’t create a global variable; you sure can, but how you do it is slightly different. Java offers the keyword–static, which you can use to create static variables to achieve similar functionality. Moreover, this type of variable is typically declared at the initial part of a class.
What are local variables?
Unlike global variables, local variables are declared inside a method, constructor, or block. The key distinction is that they are only accessible within the limited scope of that method, constructor, or block and not from other parts of the program.
Let’s look at an example of how to declare a local variable in Java:
public class LocalVariable {
public static void main(String[] args) {
int localVar = 10; // This is a local variable
System.out.println(localVar);
}
}Code language: Java (java)
In the above example, localVar would not be accessible outside of the main method. That is because the variable’s scope is limited to the main method it has been declared in.
What are static variables?
When you have a static variable in a Java class, such a variable will be shared among all instances of that class. As mentioned previously, these variables are declared through the use of static keyword and belong to the class rather than any specific instance. This means you can access a static variable without creating an instance of the class.
Static variables may also be called static fields or class variables in Java.
What are instance variables?
Instance variables are non-static variables declared in a class but outside any method, constructor, or code block. Each instance of the class has its own copy of the instance variables.
Here’s an example that uses instance variables:
public class InstanceVariableExample {
int instanceVar; // This is an instance variable
public static void main(String[] args) {
InstanceVariableExample obj = new InstanceVariableExample(); // Create an instance of the InstanceVariableExample class
obj.instanceVar = 5; // Set the instance variable for the created object
System.out.println(obj.instanceVar); // Print the instance variable of the created object
}
}
Code language: Java (java)
Let’s review the code:
In line two, we declared an instance variable named instanceVar. Line four has the main method, which is the entry point of our program. Then, on line five, we create a new instance of the InstanceVariableExample class and assigns it to the variable obj while line six sets the instanceVar of the obj instance to 5. Lastly, line seven prints the value of instanceVar for the obj instance, which is 5.
How about we create another instance of the InstanceVariableExample class?
public class InstanceVariableExample {
int instanceVar;
public static void main(String[] args) {
InstanceVariableExample obj = new InstanceVariableExample();
obj.instanceVar = 5;
System.out.println(obj.instanceVar);
InstanceVariableExample obj2 = new InstanceVariableExample(); // Create another instance of the InstanceVariableExample class
obj2.instanceVar = 10; // Set the instance variable for the second object
System.out.println("obj2 instanceVar: " + obj2.instanceVar); // Print the instance variable of the second object
// Print the instance variable of the first object again to show that it's independent of the second object
System.out.println("obj1 instanceVar (after modifying obj2): " + obj1.instanceVar);
}
}
Code language: Java (java)
Program output:
obj2 instanceVar: 10
obj1 instanceVar (after modifying obj2): 5
The modified sample code created a new class instance in line nine. In the next line, we set the instance variable of the newly created object to 10. Line 11 prints the value of instanceVar of the second object, which is 10. Lastly, line 14 prints the value of instanceVar for the first object again to show that it remains 5 and that it is independent of the value set for obj2 instance.
This demonstrates that each instance of the InstanceVariableExample class has its own copy of the instanceVar instance variable. Modifying the instanceVar in one instance does not affect the instanceVar in another instance.
How to create a global variable in Java
You can use a static variable to create a global variable in Java. As stated earlier, a static variable is associated with the class rather than any particular class instance. This allows the variable to be accessed from anywhere in the program using the class name.
Let’s look at an example:
public class GlobalVariableExample {
// Declare a static variable
public static int globalVar = 100;
public static void main(String[] args) {
// Access the static variable directly using the class name
System.out.println(GlobalVariableExample.globalVar);
// Modify the static variable
GlobalVariableExample.globalVar = 200;
// Access the static variable from another method
anotherMethod();
}
public static void anotherMethod() {
// Access the static variable
System.out.println(GlobalVariableExample.globalVar);
}
}Code language: Java (java)
Program output:
100
200
In this example, the variable name of our global variable is globalVar; a static variable (or static field) acts as a global variable. It can be accessed and modified from the main method and from the anotherMethod method.
As you can see, although there is no true global variable in Java, it is still possible to create global-like variables.
Java global variable between classes
You can also access the static variable from a different class in the same program. Here’s an example demonstrating this:
public class AccessGlobalVariable {
public static void main(String[] args) {
// Access the static variable from GlobalVariableExample class
System.out.println(GlobalVariableExample.globalVar);
// Modify the static variable
GlobalVariableExample.globalVar = 300;
// Print the modified value
System.out.println(GlobalVariableExample.globalVar);
}
}Code language: JavaScript (javascript)
Program output:
100
300
Please note that a global variable cannot be modified if the static and final keywords are used when the global variable is created. The final keyword makes variables constant (non-changing) in Java.
In this example, the AccessGlobalVariable class accesses and modifies the globalVar static variable defined in the GlobalVariableExample class. This demonstrates how static variables can be used as global variables, accessible from different classes within the same program.
Default values of uninitialized static variables
We will end with a note on default values for uninitialized static variables. In Java, if you declare a static variable but do not initialize it, it will have an initial value depending on its data type:
- Numeric types (byte, short, int, long, float, double):
0or0.0 - char:
\u0000(null character) - boolean:
false - Object references (including arrays):
null
Here is an example to demonstrate this:
public class DefaultStaticValues {
public static int defaultInt; // Default value 0
public static double defaultDouble; // Default value 0.0
public static boolean defaultBoolean; // Default value false
public static String defaultString; // Default value null
public static void main(String[] args) {
System.out.println("Default int value: " + defaultInt);
System.out.println("Default double value: " + defaultDouble);
System.out.println("Default boolean value: " + defaultBoolean);
System.out.println("Default String value: " + defaultString);
}
}
Program output:
Default int value: 0
Default double value: 0.0
Default boolean value: false
Default String value: nullCode language: Shell Session (shell)
Final thoughts on creating global variables in Java
While Java does not have a concept of global variables in the traditional sense, you can achieve similar functionality using static variables. Static variables belong to the class rather than any particular instance, allowing them to be accessed using the class name from any part of the program. Understanding the different types of variables in Java—local variables, instance variables, and static variables—will help you effectively manage data within your programs, whether for software testing, mobile development, data analysis, or even for learning design patterns.
Related articles
Follow our blog
Be the first to know when we publish new content.
What is global variable in Java?
- How to Exit A Program in Java - June 16, 2024
- How to Get User Input in JavaScript - June 7, 2024
- How To Calculate Percentage In Java - June 1, 2024