Global variables in Java
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
In Java, global variables are not termed as "global" per se as seen in other programming languages like C or JavaScript. Instead, Java, being a class-based object-oriented programming language, manages state via fields (variables) within classes. Among these, variables declared as public and static can be used in a manner akin to global variables, allowing them access from any other class within the application without creating an instance of the class in which they are defined.
Understanding Static Fields
Static fields or class variables are shared among all instances of a class. Declaring a variable as static helps it work like a global variable. Here’s how you define them:
In this example, globalCounter is accessible from any class in the application by referencing it through the class name, like GlobalData.globalCounter.
When to Use Static Variables
- Shared Data: When a particular piece of data is to be shared across various instances of a class.
- Constants: For constant values, which are not meant to change and are accessible across the application.
- Utility Functions: When a method (utility function) needs to be accessible without having to instantiate the class.
Impact of Using Global-like Variables in Java
While these variables offer convenience and simplify access to shared data across different parts of an application, they must be used judiciously due to several reasons:
- Security: Global-like variables can be modified from any part of the application, which can lead to accidental or unauthorized changes.
- Testing and Debugging: Static fields can hold state, which may persist between tests and lead to non-deterministic behaviors.
- Memory Management: Since static fields are not tied to any specific instance, they remain in memory as long as the application is alive, potentially leading to higher memory usage and leaks if not managed correctly.
Best Practices for Using Static Variables
To mitigate some of the risks and maintain code quality:
- Minimize Visibility: Use the least visibility required. If the variable does not need to be accessed outside the package, use package-private or protected visibility.
- Final Keyword: Mark static variables as
finalif they are constants. This will prevent them from being re-initialized. - Encapsulation: Use getter and setter methods to access static fields. This can help in adding validation, logging, or other controls over how these fields are accessed or modified.
Example: Implementing Global Configuration
Here’s a practical use of static fields to hold application-wide configuration settings:
In this example, APP_VERSION is a constant accessible throughout the app, while debugMode is controlled through getter and setter.
Summary Table
| Feature | Description | Example | Best Practice |
| Static Fields | Variables declared with static modifier, shared among all instances. | public static int count; | Use for shared data or constants. |
| Visibility | Access level of the variable. | public, protected, private | Use the most restrictive visibility needed. |
| Final Fields | Variables that are constants. | public static final String VERSION = "1.0"; | Mark as final if not intended to be changed after initialization. |
| Encapsulation | Accessing static fields via methods. | public static int getCount() { return count; } | Use getters/setters to control access. |
Conclusion
In Java, although there’s no direct feature termed as "global variables," static fields provide a similar functionality. Proper use of static fields involves understanding their lifecycle, scope, visibility, and associated best practices to ensure that they enhance functionality without introducing risks or bad design decisions into your application.
Related reading
- Good examples using java.util.logging
- Good Java graph algorithm library?
- Good Java graph algorithm library?
- Good practice when using kafka with jpa
- Good reasons to prohibit inheritance in Java?
- google-services.json for different productFlavors
- Google Guava vs. Apache Commons
- GoTo Next Iteration in For Loop in java

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.