Java Global Variables

In this article, we will see what is a global variable and how we can use this in our Java programs.

In Java, all the functions and data members are declared inside a class and every declaration has to be done inside it. If we declare them outside the class, then they would not be accessible by the object of that class.

Therefore, in Java, there is no such precise concept of global variables because these are described at the top of a program which is not possible in the Java language.

In Java, we can use the static keyword to implement the concept of global variables. When we create a static variable or static method, it is assigned a special area inside a heap (space where all class objects get stored).

You can use static variables instead of global variables in Java. They are part of a class and are accessible by any object of that class.

Syntax:

Program for Global Variable Declaration in Java

Output:

If a static variable is not initialized, then the default value of the static variable is zero.

Output:

Static variables can also be accessed by using className.

Program:

Output:

There is a condition that if we do not create an object, then we cannot access the static variable and it shows an error.

But, there is another way to access static variables without creating an object. We can use a static keyword along with the function name in which the static variable is used and then calling the function inside the main method to access its value.

Output:

Benefits of Static Variable

  • When we use the same data in multiple functions, instead of declaring data multiple times we can use a static variable and access it in multiple functions with the help of an object.
  • Static variables take memory only once in the class area at the time of class loading.
  • Even if we do not create an object of the class, we can access the static variable using a static keyword along with the function in which it is used, and then calling the function in the main method and alternatively access it using className too.

Limitations of Static Variable

  • Static members always take up memory whether it is in use or not. We cannot control the creation and destruction of static variables. It is constructed when the execution of the program starts and it is destructed when the program unloads (or when JVM shuts down).

So, that’s all about global variables in Java. You can ask your queries in the comment section.

Leave a Comment

Your email address will not be published. Required fields are marked *