Global variables in Java


How do you define Global variables in Java ?

6/6/2014 2:03:27 PM

Accepted Answer

To define Global Variable you can make use of static Keyword

public class Example {
    public static int a;
    public static int b;

now you can access a and b from anywhere by calling


5/26/2014 3:49:55 PM

You don't. That's by design. You shouldn't do it even if you could.

That being said you could create a set of public static members in a class named Globals.

public class Globals {
   public static int globalInt = 0;

but you really shouldn't :). Seriously .. don't do it.


Another way is to create an interface like this:

public interface GlobalConstants
  String name = "Chilly Billy";
  String address = "10 Chicken head Lane";

Any class that needs to use them only has to implement the interface:

public class GlobalImpl implements GlobalConstants
  public GlobalImpl()

You are better off using dependency injection:

public class Globals {
    public int a;
    public int b;

public class UsesGlobals {
    private final Globals globals;
    public UsesGlobals(Globals globals) {
        this.globals = globals;

Lots of good answers, but I want to give this example as it's considered the more proper way to access variables of a class by another class: using getters and setters.

The reason why you use getters and setters this way instead of just making the variable public is as follows. Lets say your var is going to be a global parameter that you NEVER want someone to change during the execution of your program (in the case when you are developing code with a team), something like maybe the URL for a website. In theory this could change and may be used many times in your program, so you want to use a global var to be able to update it all at once. But you do not want someone else to go in and change this var (possibly without realizing how important it is). In that case you simply do not include a setter method, and only include the getter method.

public class Global{
    private static int var = 5;

    public static int getVar(){
        return Global.var;

    //If you do not want to change the var ever then do not include this
    public static void setVar(int var){
        Global.var = var;

There is no global variable in Java

Nevertheless, what we do have is a static keyword and that is all we need. Nothing exists outside of class in Java. The static keyword represents a class variable that, contrary to instance variable, only has one copy and that transcends across all the instances of that class created, which means that its value can be changed and accessed across all instances at any point.

If you need a global variable which can be accessed beyond scopes, then this is the variable that you need, but its scope exists only where the class is, and that will be all.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]