JavaRush /Java Blog /Random EN /Global variables in Java: when to use them?
Анзор Кармов
Level 31
Санкт-Петербург

Global variables in Java: when to use them?

Published in the Random EN group
Hello! In this article we will talk about global variables, their declaration and examples of appropriate use. A small note: we will not consider global class variables, that is, those that can be accessed within any one class. We will talk about global variables of the entire application - those that can be accessed within the entire application. Global Variables in Java: When to Use Them?  - 1

How to create global variables

Global variables are variables that are accessible from anywhere in the application. In other words, their scope is the entire application. To create such a variable in Java, you need to create a public static variable in a public class:
public class Example {
    public static int a;
    public static int b;
    public static String str;
}
The variables a, band str- have become global. We can access them directly from other classes inside the application:
public class GlobalVarsDemo {
    public static void main(String[] args) {
        Example.a = 4;
        Example.b = 5;
        Example.str = "Global String variable value";

        System.out.println(Example.a);
        System.out.println(Example.b);
        System.out.println(Example.str);
    }
}
If we run the method main, we will see the following output:

4
5
Global String variable value
Global variables can be divided into 2 types:
  • variables that can be edited;
  • variables that can only be read.
The latter are called global constants. In order to create a global constant, you need to make a variable finaland assign a value to it when defining the variable:
public class Constants {

    public static final double PI = 3.1415926535897932384626433832795;
    public static final String HELLO_WORLD_STR = "Hello, World!";

}
According to the Java naming convention, all constants must be named in upper case, separating words with an underscore character. So, we have created constants, and now we will not be able to change their values: Global Variables in Java: When to Use Them?  - 2However, we can read their values:
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println(Constants.HELLO_WORLD_STR);
    }
}
Conclusion:

Hello, World!
public class ConstantsDemo {
    public static void main(String[] args) {
        double r = 10;
        String message = String.format("Площадь круга с радиусом %f=%f", r, getCircleSquare(r));
        System.out.println(message);

    }

    static double getCircleSquare(double r) {
        return Constants.PI * r * r;
    }
}
Conclusion:

Площадь круга с радиусом 10,000000=314,159265

Should you use global variables?

There are many articles on the Internet, the main message of which is this: global variables are evil, bad and terrible. Is it really? Let's try to give the pros and cons of global variables so that everyone can draw their own conclusion. Global Variables in Java: When to Use Them?  - 3Let's start with the cons. Let's imagine an application that has a class with global variables that can be read and edited. Over time, the number of classes in the project, the number of global variables and methods that use global variables, or in other words, depend on them, grows. Over time, each global variable is read in different parts of the system for different purposes. In different parts of the system, the value of a variable can be updated. The overall picture of the world of this application becomes significantly more complicated, and this leads to the following disadvantages :
  1. Reduced readability and increased difficulty in understanding code.
  2. Increased complexity of code maintenance.
  3. To change one global variable, it is necessary to analyze the entire code so as not to set the variable to a value that is invalid for other parts of the system.
  4. Increase in errors that are very difficult to debug.

    Let's imagine a global variable, an array of objects. In one part of the system, for example, strings are expected in this array, and in another part of the system, someone decided to use floating point numbers. It’s unlikely that anyone would want to understand this.

  5. The variable names may be the same if you use global variables in your code, as well as some libraries that, in turn, also use global variables. This can lead to errors both on the side of your application and on the side of the library you are using.
  6. Increases connectivity between different parts of the system that use global variables. On the contrary, you should strive for loose coupling of the code. It's better to have many small subsystems loosely connected to each other than to have one hefty thing. Because it is easier for the brain to deal with several simple things than with one too complex and confusing thing.
  7. Writing unit tests becomes more difficult because the test does not know which global variables are needed and how they need to be initialized.
  8. In multithreaded applications, the use of global variables by different threads leads to an increase in errors that are difficult to debug and to an increase in project complexity. Because of this, it is necessary to configure access to such variables more correctly, equipping them with synchronizations and locks. This may lead to short circuits in the future. For example, thread A has locked variable X for its work, and thread B has locked variable Y for its work, and thread A now needs variable Y, and thread B needs variable X. As a result, the program will freeze.
But this is all inaccurate. This is a description of risks, the likelihood of which increases as the project grows and the number of global variables in it increases. Let's move on to the pros :
  1. In small projects, global variables are the simplest thing to make the project work.
  2. Sometimes the fear of using global variables leads to even more complexity in the project. Then programmers start creating singletons and resorting to other design patterns.
  3. In programming, you often need to rely on some immutable values.

    The most reasonable thing is to write such values ​​as a constant, because only constants guarantee that the value of a variable will not change over time. Such constants can be found all the time ( Integer.MAX_VALUE, Integer.MIN_VALUE, Boolean.TRUE, Collections.EMPTY_LISTetc.). But programming is not limited to using standard libraries. It often happens that you need to write some kind of unique logic, which will need to rely on your own unique constants. That's why sometimes using constants (read-only global variables) really makes life easier.

In general, you should not overuse global variables; if possible, use only constants. It was said earlier that using global variables in small projects is not bad. But it is better for a novice developer not to use them at all. For two reasons:
  1. Everything that a novice developer writes is essentially a small project. And using global variables in his projects will teach him to use global variables everywhere.
  2. It is better to first learn to do without “forbidden tricks”. And with experience, the understanding of when it is appropriate to use such techniques will come on its own.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION