Using Global Variables/Constants in Java

Introduction

Java's object-oriented code structure can make referencing variables in multiple places more difficult. It can also be difficult at times to decide which class a given variable should be a part of, especially if it's a widely used value like a database connector or mathematical constant.

In many languages, when faced with a problem like this, we can declare a global variable. Though, unfortunately, Java doesn't technically allow the creation of variables in a global scope.

In this article, we'll go over emulating and using global variables in Java.

What is a Global Variable?

A global variable is a variable which can be accessed from any scope. Many programming languages feature special syntax for declaring a global variable, for example, Python lets us use the global keyword:

global a_variable = 5

C creates globals by simply declaring a variable outside a function.

int aVariable = 3;

int someFunction() {
    print(aVariable);
}

Regardless of the syntax for creating the global variable, they work more or less the same way. They allow you to access and modify the value from inside any other class or function. This can cause problems if you try to re-use the name in another scope. For example:

int aVariable = 3;

int someFunction() {
    int aVariable = 7;
    print(aVariable);
}

Depending on the language, this is generally handled in one of three ways:

  • Throw an error for declaring a variable that already exists.
  • Assume the print statement references the local variable.
  • Assume the print statement references the local variable unless special syntax is used to reference the global.

The third method is how Java handles instance variables when a method parameter uses the same name. Picture a class with a variable declared as private int number. To modify the value of number later on, you could create a function:

public int setNumber(int number) {
    this.number = number;
}

The this keyword shows that you want the number from the class, not from the method parameters.

Why Doesn't Java use Global Variables?

The short answer to this question is: intentional design. Java was created as a purely object-oriented programming language, which is why everything you create is wrapped in a class.

By being purely object-oriented, developers are encouraged to keep related variables and functions together, making the program as a whole more organized. This can also help with identifying the purpose of a poorly documented variable. For example:

class GridCoordinate {
    int x;
    int y;
}

Without the knowledge that these variables were part of a GridCoordinate class, it would be near impossible to identify them. With the context of the class name, we can infer they are the horizontal and vertical positions of a given point on a grid.

Now picture you're working as part of a fully remote team with members around the globe. You and a coworker on another continent are both working on the same file when you both come across this:

global ver = 2.55

You make the assumption that the variable represents a version number. Your coworker thinks it might have something to do with a vertical axis. You both make changes to different functions based on your assumptions, modifying and referencing the value as you see fit.

This is the type of situation that Java tries to avoid by not having global variables. Using global variables in a large project can lead to unintended and unexpected behavior as variables are declared and modified in different sections of the code.

How to Emulate a Global Variable in Java?

Though there are some drawbacks to global variable use, there are times that you may want a variable to be accessed in many places, but you may feel that it doesn't warrant creating a dedicated wrapper class.

For example, you may want to reference your database connection in multiple classes, but haven't declared a DatabaseConnection class to handle all of your database functionality. You may also just prefer to just use the built-in methods from the database library of your choice without a wrapper to handle transactions.

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Usually, you can create a Constants or a Reference class, where you keep various "global" values stored if they're used commonly in other parts of the application. A single variable doesn't necessarily warrant an entire class, so you can encompass many of them in a single Reference or Constants class:

public class Reference {
    public static final double VERSION_NUMBER;
    public static final String DATABASE_URL;
    public static final Database DATABASE;
}

These variables can then be accessed elsewhere by referencing the class:

public int someMethod() {
    System.out.println(Reference.VERSION_NUMBER);
}

Having the Reference class makes it easy to know where to look for comments explaining the purpose of the variable. Had the variables above been created as true global variables, it's likely they would have been created in different files, making it harder to find the author's intended purpose.

A better way to use the Reference class would be to treat all variables as private, and use getter methods to control all access to the values. It is also wise to use constants instead of variables for data that should not change while the program is running. For example:

private static final String DATABASE_URL = "https://databaseurl.db/database";
private static final Database DATABASE = Database.connect(databaseURL);

public static Database getDatabase() { return DATABASE; }
public static String getUrl() { return DATABASE_URL}

In this example, the database URL and database connection cannot be modified anywhere else in the code, but the database connection can be referenced as needed for transactions.

While this isn't quite as clean syntactically as defining a global variable, it can provide the same level of freedom.

Another common usage would be to define some constants in an application that has immutable values that you use often. For example, if you're training a Neural Network or running Genetic Algorithms, you'll have various values used all over the place:

public static final int GENERATION_SIZE;
public static final int GENOME_SIZE;
public static final int REPRODUCTION_SIZE;
public static final int MAX_ITERATIONS;

Then, you'd access these through their public class, such as:

for(int i = 0; i < Constants.MAX_ITERATIONS; i++) {
  // ...
}

Conclusion

Global variables are often seen as a divisive topic, with many developers saying they should never be used. These developers generally argue that global variables make the code harder to maintain. There are, however, some instances where global-like variables are useful so long as they are well organized and clearly identified.

Ultimately, the decision to use them falls on you or a senior member of the development team.

In this article, we've gone over how to emulate global variables in Java.

Last Updated: November 30th, 2020
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

© 2013-2024 Stack Abuse. All rights reserved.

AboutDisclosurePrivacyTerms