Global Variables in Java

Global variables in Java

A global variable is a variable that is accessible anywhere else in the code. Some languages, like Python, explicitly allow the creation of global variables. They can be convenient to use and can also reduce the size of the code base because a global variable never needs to be declared more than once.

However, global variables have several important problems that must be considered whenever they are used.

By design, the Java programming language doesn’t have global variables. There are ways of getting around this, and we will see how to do so in this article.

However in order to understand global variables, we need to first get into why they aren’t built into Java the way that local variables, instance variables, and static variables are. To make things a little more complicated, instance variables are sometimes referred to as ‘global variables’ in Java, although they aren’t true global variables.

In this article, we’ll get into each of these topics, including: what are global variables, why are global variables considered ‘bad’ or risky, when is it okay to use global variables and how to create variables that function globally to make our lives easier when appropriate.

What Are Global Variables?

Since Java technically doesn’t have global variables, we have to assume that we are referring to the common definition from within the field of computer science. In general, a global variable is simply a type of variable that can be accessed anywhere in a program, including inside functions.

They are typically declared outside any function or class, giving them a scope that isn’t limited to that function or class.

Global variables can make it easy to write code because they can simplify the process of working with variables. This is especially true in scripting languages where we often don’t require a high degree of complexity. For writing a very short script, global variables can be handy and often don’t result in any negative consequences. However as the codebase grows, the likelihood of having issues with global variables increases.

The Issues With Global Variables

There are several problems with global variables that are frequently cited, including reduced flexibility and modularity, and the propagation of any changes made to a global variable across the entire program.

They can also present issues with concurrency as well as testing and debugging. Finally, they also open the possibility of a security issue, particularly if used to store sensitive data.

Perhaps the biggest problem with global variables is that any changes will propagate throughout the entire codebase. This is actually the root cause of many of the issues with global variables. It can lead to unpredictable and possibly unsafe behavior, and can make a larger codebase more difficult to maintain for these reasons.

An interrelated issue is reduced flexibility and modularity. Because global variables can be accessed from multiple locations, they break the principle of encapsulation, which states that the internal state of an object should be shielded from the outside.

Because global variables can be accessible at multiple places in the code, they can introduce concurrency issues, such as race conditions. If multiple threads try to modify global variables simultaneously without proper synchronization, it can lead to data corruption and unexpected behavior.

Unit testing can become difficult because global variables may have different values in different parts of the program. This can make it hard to isolate specific behaviors for testing. Debugging also becomes more complicated because changes to global variables can affect the behavior of multiple functions or modules.

For all these reasons (and more), global variables are often proscribed and avoided by many programmers. They often just aren’t worth the risks.

However, there are occasions when global variables can be handy and it’s worth understanding how we can get around these issues and work with global variables on a limited basis. At the very least, it’s an interesting case study allowing us to learn a little more about variables in Java.

The Safe Way to Use Global Variables in Java?

Many senior programmers would argue that there is no ‘safe’ way to use global variables. However it’s worth thinking about how they might be able to be used safely in a limited fashion. For that reason, I would specify a few minimum conditions for their usage:

  1. Once assigned, the value of a global variable should never be changed.
  2. Global variables should only be used in short programs where the entire codebase is easily manageable.
  3. Global variables should never be used in production code.

However I want to also specify that in addition to these, you should always be conservative and use your own judgement. This list is not exhaustive and is only intended as a suggestion for how to use global variables more safely. Nothing can actually make them safe.

The Value of a Global Variable Should Never be Changed

By treating a globally used variable like a constant, we eliminate many of the issues that can occur when using them. We won’t need to worry about the value changing elsewhere in the code, meaning that concurrency issues won’t happen either.

Global Variables Should Only be Used in Short Programs

To keep things as safe as possible, only use global variables in short applications where we can easily identify any possible issues. This also serves to reduce the potential of anything bad occurring to begin with.

Global Variables Should Never be Used in Production Code

Global variables present way too many risks to ever allow them to come close to production code. Only use them in non-production environments that will never be shared outside and have no chance of accidentally being included in production code.

How to Use Variables Globally in Java

Now that we’ve covered some bare-minimum requirements for using global variables in a way that would minimize any potential real-life impact, let’s see how we can get around the fact that Java doesn’t include global variables by design.

We can use the keyword static to create variables that can be accessed globally.

For example:

public class GlobalExample { 
    public static int foo = 21; 
    public static int bar = 42; 
}

In order to access the variables foo and/or bar, we can call them using dot notation:

GlobalExample.foo;
GlobalExample.bar;

To conclude this article and round out our understanding of variables in Java, I’ve included a short review of variable types.

Types of Variables in Java

It can be helpful to compare our example of globally-accessible variables with instance, static, and local variables.

Instance Variables

An instance variable is declared inside a class but outside any method

Every object of the class has its own copy of the instance variables.

The following example shows how we can declare an instance variable:

public class MyClass { 
    int instanceVariable = 10; 
}

Static Variables

A static variable (also called a class variable) is shared among all objects of a class. Static variables are declared with the `static` keyword, and are sometimes considered to be global because they are shared between objects. However, they aren’t truly global variables because they are not shared outside of the class.

The following example shows how to declare a static, or class variable:

public class MyClass { 
    static int staticVariable = 5; 
}

Local Variables

A local variable is declared inside a method or block. Local variables are visible only within the method or block where they are declared.

public void myMethod() { 
    int localVar = 42; 
}

Variables are fundamental to programming in Java, as they allow developers to store and manipulate data, making programs dynamic and responsive to various inputs and conditions.

Conclusion – Global Variables in Java

In this article, we’ve explored the concept of global variable in Java.

Since Java doesn’t inherently support global variables (e.g. there is no ‘global’ keyword), it is important to consider the reasons for this before attempting to circumvent it. We saw ways to make the use of global variables a bit more safe, and we saw an example of how we can make use of the static keyword to work with variables globally. Finally, we reviewed instance, static, and local variables in Java in order to round out our understanding of how variables are used within the Java ecosystem.

Hopefully you’ve found this Java tutorial to be helpful. Please check out our other Java tutorials, as well as the complete course on Java, for additional support in your Java programming journey.