How do you define Global variables in Java ?
-
23Can you tell us *why* you want to define global variables in Java? – Adam Paynter Jan 10 '11 at 12:02
-
53To access the variable from outside the class – aTJ Jan 10 '11 at 12:05
-
7Perhaps you should edit your question to include some sample code illustrating precisely what you want. It would help us recommend the best solution. – Adam Paynter Jan 10 '11 at 12:08
-
8@Adam :I should be able to change the value of a variable in one class from another class. – aTJ Jan 10 '11 at 12:32
-
4You don't. There are no global variables in Java. – user207421 Apr 30 '18 at 04:49
-
@aTJ I thought global variables should be accessible by all private (or more lightly restricted) methods, in the same class, i.e. member variables in java. – HellishHeat Dec 16 '21 at 08:56
25 Answers
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
Example.a;
Example.b;
-
18Be careful when doing this - when the Global class gets unloaded the variables will be undefined null. If you sell your app this will happen sooner or later and you keep looking for error everywhere but not there.... – user387184 Nov 05 '11 at 19:55
-
11The `static` keyword makes variables globally accessible, while their class is loaded. – sjas Jan 29 '12 at 13:22
-
27About class unloading: if there is any strong reference chain from any GC Root to an instance of Global or its children, or any compile-time reference from a loaded and not-unloadable class to Global, then the Class object relative to Global is strongly reachable, and, therefore, so is the ClassLoader that loaded Global; which makes it impossible to unload Global (since class unloading can only happen after the GC completely removes any strong reference to the ClassLoader that loaded a given class). If you have no references at all, how could the unloading be a problem??? – Bruno Reis Jul 25 '13 at 01:59
-
7@Abi I'd suggest your rename your class from `Global` to something else (`TestClass`?) in order not to give people the impression that there is such a thing as a `Global` Java keyword. Better safe than sorry :) – Nicolas Rinaudo Jul 25 '13 at 13:36
-
@user387184 To conclude, the values won't suddenly get null as long as there are references to that "global" class, right? – amey91 Aug 17 '14 at 00:47
-
1How those variables are going to work when modified and read from multiple threads, why not ... public static volatile int a; – Sergey Shcherbakov Nov 15 '21 at 21:42
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.

- 145,806
- 30
- 211
- 305

- 12,041
- 1
- 29
- 33
-
1as I have written above - when the class gets unloaded the variables loose their values to null and your app will crash. – user387184 Nov 05 '11 at 19:57
-
8Then what's the better approach that I can declare constants so that all class methods can access them? – Alston Jun 11 '14 at 11:35
-
10Posts of this nature is the reason novices develop global variable phobia, and then we see all sorts of egregious techniques being devised to circumvent the global variable taboo, but achieve the same effect. – Evgeni Sergeev Apr 29 '15 at 08:28
-
60Down vote for saying, "don't do it." without explaining or referring to an explanation of why. – Jeff McCune Jun 10 '15 at 23:08
-
17
-
How that variable is going to work when modified and read from multiple threads, why not ... public static volatile int globalInt; – Sergey Shcherbakov Nov 15 '21 at 21:44
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()
{
System.out.println(name);
}
}

- 472
- 3
- 10

- 3,115
- 7
- 40
- 61
-
I'm wondering why this answer has (before mine) no up-votes. Does it not provide a reasonable alternative answer to that provided by all the other answers? – M_M Aug 19 '12 at 21:29
-
-
can you explain your point please? never been bad practise and please no need to vote down, thanks :) – Evan Lévesque Apr 15 '13 at 16:45
-
22Effective Java by Joshua Bloch, Chapter 4: Classes and Interfaces, Item 19: Use interfaces only to define types "The constant interface pattern is a poor use of interfaces." This book is worth reading! :) – MariuszS Apr 15 '13 at 20:37
-
And another comment from this book: "Constant interface antipattern - do not use!" – MariuszS Apr 15 '13 at 20:43
-
1Additionally from JDK 1.5+ you can use static import for your global variables, implementing is not needed. – MariuszS Apr 15 '13 at 20:50
-
12.... Right, that doesn't actually explain anything, that just says that some book said it was bad. – linkhyrule5 Aug 02 '13 at 20:38
-
18Here is a quote for you. Oracle says: "In order to get around this, people sometimes put static members into an interface and inherit from that interface. This is a bad idea. In fact, it's such a bad idea that there's a name for it: the Constant Interface Antipattern (see Effective Java Item 17). The problem is that a class's use of the static members of another class is a mere implementation detail. When a class implements an interface, it becomes part of the class's public API. Implementation details should not leak into public APIs." – Jolta Apr 01 '15 at 08:22
-
The link where the above quote from oracle is: https://docs.oracle.com/javase/8/docs/technotes/guides/language/static-import.html – AK S Sep 26 '19 at 09:47
-
Well as dirty as this way to implement global variables may be, I like it! Thank you Evan, you safe me time and make my code look better. – Seth Feb 26 '20 at 05:48
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;
}
}

- 20,545
- 20
- 91
- 102

- 525,659
- 79
- 751
- 1,130
-
5True, though I think your use of "Globals" confuses things a bit :-). Something like "Parameters" would be more fitting since it's not necessarily Global. – Mark Peters Jan 10 '11 at 15:46
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;
}
}

- 37,180
- 14
- 90
- 125

- 6,807
- 10
- 53
- 88
-
-
1That is not a valid java command. I dont believe it would even compile. – Dan Ciborowski - MSFT Sep 07 '21 at 03:19
-
Do you mean the class declaration is invalid if we make `Global.java` file? I actually made your "Global" class as a sub class. – Cloud Cho Sep 07 '21 at 17:02
Truly speaking there is not a concept of "GLOBAL" in a java OO program
Nevertheless there is some truth behind your question because there will be some cases where you want to run a method at any part of the program. For example---random() method in Phrase-O-Matic app;it is a method should be callable from anywhere of a program.
So in order to satisfy the things like Above "We need to have Global-like variables and methods"
TO DECLARE A VARIABLE AS GLOBAL.
1.Mark the variable as public static final While declaring.
TO DECLARE A METHOD AS GLOBAL.
1. Mark the method as public static While declaring.
Because I declared global variables and method as static you can call them anywhere you wish by simply with the help of following code
ClassName.X
NOTE: X can be either method name or variable name as per the requirement and ClassName is the name of the class in which you declared them.

- 524
- 11
- 23
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.
Nothing should be global, except for constants.
public class MyMainClass {
public final static boolean DEBUGMODE=true;
}
Put this within your main class. In other .java files, use it through:
if(MyMainClass.DEBUGMODE) System.out.println("Some debugging info");
Make sure when you move your code off the cutting room floor and into release you remove or comment out this functionality.
If you have a workhorse method, like a randomizer, I suggest creating a "Toolbox" package! All coders should have one, then whenever you want to use it in a .java, just import it!

- 4,307
- 1
- 15
- 14

- 132
- 1
- 5
There is no such thing as a truly global variable in Java. Every static variable must belong to some class (like System.out), but when you have decided which class it will go in, you can refer to it from everywhere loaded by the same classloader.
Note that static variables should always be protected when updating to avoid race conditions.

- 73,784
- 33
- 194
- 347
-
1java doesnt provide global variable functionally but if you want to have a global variable concept, we can make use of static keyword – Abi Jan 10 '11 at 12:25
Understanding the problem
I consider the qualification of global variable as a variable that could be accessed and changed anywhere in the code without caring about static/instance call or passing any reference from one class to another.
Usually if you have class A
public class A {
private int myVar;
public A(int myVar) {
this.myVar = myVar;
}
public int getMyVar() {
return myVar;
}
public void setMyVar(int mewVar) {
this.myVar = newVar;
}
}
and want to access and update myvar
in a class B,
public class B{
private A a;
public void passA(A a){
this.a = a;
}
public void changeMyVar(int newVar){
a.setMyvar(newVar);
}
}
you will need to have a reference of an instance of the class A and update the value in the class B like this:
int initialValue = 2;
int newValue = 3;
A a = new A(initialValue);
B b = new B();
b.passA(a);
b.changeMyVar(newValue);
assertEquals(a.getMyVar(),newValue); // true
Solution
So my solution to this, (even if i'm not sure if it's a good practice), is to use a singleton:
public class Globals {
private static Globals globalsInstance = new Globals();
public static Globals getInstance() {
return globalsInstance;
}
private int myVar = 2;
private Globals() {
}
public int getMyVar() {
return myVar;
}
public void setMyVar(int myVar) {
this.myVar = myVar;
}
}
Now you can get the Global unique instance anywhere with:
Globals globals = Globals.getInstance();
// and read and write to myVar with the getter and setter like
int myVar = globals.getMyVar();
global.setMyVar(3);

- 337
- 1
- 9
public class GlobalClass {
public static int x = 37;
public static String s = "aaa";
}
This way you can access them with GlobalClass.x
and GlobalClass.s

- 13,028
- 11
- 47
- 73
If you need to update global property, a simple getter/setter wrapper class can be used as global variable. A typical example is shown below.
public class GlobalHolder {
private static final GlobalHolder INSTANCE = new GlobalHolder();
private volatile int globalProperty;
public static GlobalHolder getInstance() {
return INSTANCE;
}
public int getGlobalProperty() {
return globalProperty;
}
public void setGlobalProperty(int globalProperty) {
this.globalProperty = globalProperty;
}
public static void main(String[] args) {
GlobalHolder.getInstance().setGlobalProperty(10);
System.out.println(GlobalHolder.getInstance().getGlobalProperty());
}
}

- 898
- 1
- 11
- 25
Creating an independent file, eg. Example.java to use the 1st solution, is just fine. You can do that also within the app, if e.g. the global variables are special to your current app, etc.:
Create a class at the beginning and declare your variables in there:
class Globals {
static int month_number;
static String month_name;
}
You can then access these variables -- using them as 'Globals.month_number', etc. -- from averywhere in your app.

- 3,115
- 25
- 28
-
Instead of downvoting, can you please tell me what is wrong with this solution? I am using it on a constant basis and it is the most convenient one. So I cannot do otherwise that considering this downvote as a personal thing or just done by a stupid person. – Apostolos Dec 23 '17 at 09:34
public class GlobalImpl {
public static int global = 5;
}
you can call anywhere you want:
GlobalImpl.global // 5
As you probably guess from the answer there is no global variables in Java and the only thing you can do is to create a class with static members:
public class Global {
public static int a;
}
You can use it with Global.a
elsewhere. However if you use Java 1.5 or better you can use the import static
magic to make it look even more as a real global variable:
import static test.Global.*;
public class UseGlobal {
public void foo() {
int i = a;
}
}
And voilà!
Now this is far from a best practice so as you can see in the commercials: don't do this at home

- 7,378
- 4
- 28
- 36
very simple:
class UseOfGlobal
{
private static int a;
private static int b;
}
but it is always good to have local variables defined inside method blocks where ever possible.

- 322
- 1
- 13
Generally Global variable (I assume you are comparing it with C,Cpp) define as public static final
like
class GlobalConstant{
public static final String CODE = "cd";
}
ENUMs are also useful in such scenario :
For Example Calendar.JANUARY
)

- 237,923
- 42
- 401
- 438
-
-
2
-
1no , thats what Global variable means for if you want to share that variable and change the data also then just remove `final` but it certainly depends how you want to share , where you are using and all , – jmj Jan 10 '11 at 12:13
-
-
Also note: CODE is in all caps, as its common java notation to use all caps for variables that you declare as final, and do not intend to change during the course of a program. – Dan Ciborowski - MSFT Jul 25 '13 at 01:51
There are no global variables in Java, but there are global classes with public fields. You can use static import feature of java 5 to make it look almost like global variables.

- 39,895
- 28
- 133
- 186
To allow an unqualified access to static members of another class, you can also do a static import:
import static my.package.GlobalConstants;
Now, instead of print(GlobalConstants.MY_PASSWORD);
you can use the Constant directly: print(MY_PASSWORD);
See What does the "static" modifier after "import" mean? to decide about.
And consider the answer of Evan Lévesque about interfaces to carry the Constants.

- 164
- 1
- 11
// Get the access of global while retaining priveleges.
// You can access variables in one class from another, with provisions.
// The primitive must be protected or no modifier (seen in example).
// the first class
public class farm{
int eggs; // an integer to be set by constructor
fox afox; // declaration of a fox object
// the constructor inits
farm(){
eggs = 4;
afox = new fox(); // an instance of a fox object
// show count of eggs before the fox arrives
System.out.println("Count of eggs before: " + eggs);
// call class fox, afox method, pass myFarm as a reference
afox.stealEgg(this);
// show the farm class, myFarm, primitive value
System.out.println("Count of eggs after : " + eggs);
} // end constructor
public static void main(String[] args){
// instance of a farm class object
farm myFarm = new farm();
}; // end main
} // end class
// the second class
public class fox{
// theFarm is the myFarm object instance
// any public, protected, or "no modifier" variable is accessible
void stealEgg(farm theFarm){ --theFarm.eggs; }
} // end class

- 37
- 2
-
2What does this answer add that the other answers don't? I can't see any "new" value in this answer. – EWit Jul 19 '14 at 07:31
In general, Java doesn't have any global variables. Other than local variables, all variables comes under the scope of any class defined in the program. We can have static variables to have the scope of global variables.

- 9,564
- 146
- 81
- 122

- 114
- 1
- 12
Going by the concept, global variables, also known as instance variable are the class level variables,i.e., they are defined inside a class but outside methods. In order to make them available completely and use them directly provide the static keyword. So if i am writing a program for simple arithmetical operation and it requires a number pair then two instance variables are defined as such:
public class Add {
static int a;
static int b;
static int c;
public static void main(String arg[]) {
c=sum();
System.out.println("Sum is: "+c);
}
static int sum() {
a=20;
b=30;
return a+b;
}
}
Output: Sum is: 50
Moreover using static keyword prior to the instance variables enable us not to specify datatypes for same variables again and again. Just write the variable directly.
-
1There are no global variables in Java; they are not also known as instance variables; defining them as `static` does not 'make them available completely'. First paragraph is nonsense. Example is poor practice. – user207421 Apr 30 '18 at 04:52
without static
this is possible too:
class Main {
String globalVar = "Global Value";
class Class1 {
Class1() {
System.out.println("Class1: "+globalVar);
globalVar += " - changed";
} }
class Class2 {
Class2() {
System.out.println("Class2: "+globalVar);
} }
public static void main(String[] args) {
Main m = new Main();
m.mainCode();
}
void mainCode() {
Class1 o1 = new Class1();
Class2 o2 = new Class2();
}
}
/*
Output:
Class1: Global Value
Class2: Global Value - changed
*/

- 361
- 2
- 5
Object-Oriented Programming is built with the understanding that the scope of variables is closely exclusive to the class object that encapsulates those variables.
The problem with creating "global variables" is that it's not industry standard for Java. It's not industry standard because it allows multiple classes to manipulate data asyncronized, if you're running a multi-threaded application, this gets a little more complicated and dangerous in terms of thread-safety. There are various other reasons why using global variables are ineffective, but if you want to avoid that, I suggest you resort to Aspect-Oriented Programming.
Aspect-Oriented Programming negates this problem by putting the parent class in charge of the scope through something called "advices", which adds additional behavior to the code without actually modifying it. It offers solutions to cross-cutting concerns, or global variable usage.
Spring is a Java framework that utilizes AOP, and while it is traditionally used for web-applications, the core application can be used universally throughout the Java framework (8.0 included). This might be a direction you want to explore more.

- 421
- 2
- 16
To define Global Variable you can make use of static Keyword
public final class Tools {
public static int a;
public static int b;
}
now you can access a and b from anywhere by calling
Tools.a;
Tools.b;
Yoy are right...specially in J2ME... You can avoid NullPointerException by putting inside your MidLet constructor (proggy initialization) this line of code:
new Tools();
This ensures that Tools will be allocated before any instruction that uses it.
That's it!

- 7,712
- 9
- 48
- 65

- 11
-
3Um... Sorry, but what does this add that isn't already covered by the existing answers? – Mysticial Jul 25 '13 at 01:07
-
Maybe you are right..but this answer explain things like memory allocation. – user2616742 Jul 25 '13 at 02:50
-