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;
Answer from Abi on Stack Overflow
๐ŸŒ
Quora
quora.com โ€บ Can-we-say-that-a-public-static-variable-is-a-global-variable-in-Java
Can we say that a public static variable is a global variable in Java? - Quora
Answer (1 of 6): No, you shouldnโ€™t say a public static variable is a global variable. Global variables, in the approach of procedural languages like C, Perl, etc, are accessible from anywhere in the program and are always reachable. Only one โ€œinstanceโ€ of that variable exists and its ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ using-static-variables-in-java
Using Static Variables in Java - GeeksforGeeks
September 22, 2021 - Then, a single variable is created and shared among all the objects at the class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ java โ€บ java global variable
How to Create Global Variable in Java | Delft Stack
February 2, 2024 - There is no concept of a global variable in Java. We cannot create global variables as we do in other programming languages such as C or C++. However, we can achieve this by using some existing concepts such as static and final static variables ...
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ using-global-variables-constants-in-java
Using Global Variables/Constants in Java
November 30, 2020 - 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; }
๐ŸŒ
Edureka Community
edureka.co โ€บ home โ€บ community โ€บ categories โ€บ java โ€บ how can we define global variables in java
How can we define global variables in java | Edureka Community
April 19, 2018 - 1856/how-can-we-define-global-variables-in-java ยท Home ยท Community ยท Categories ยท Java ยท How can we define global variables in java ยท how do I turn a double in an array from 1000 to infinity Jul 9, 2024 ยท I have created a code in java for a flower shop and now my IDE is showing all the inputs are in red showing there is an error Jul 6, 2024 ยท
Find elsewhere
๐ŸŒ
automateNow
automatenow.io โ€บ home โ€บ how to create global variables in java
How To Create Global Variables In Java | automateNow
June 16, 2024 - In this example, the variable name of our global variable is globalVar; a static variable (or static field) acts as a global variable. It can be accessed and modified from the main method and from the anotherMethod method.
๐ŸŒ
Medium
naveen-metta.medium.com โ€บ demystifying-local-global-instance-and-static-variables-in-java-de26971eac75
Demystifying Local, Global, Instance, and Static Variables in Java | by Naveen Metta | Medium
January 13, 2024 - In the vast landscape of Java programming, a nuanced understanding of variables is pivotal to crafting efficient and well-organized code. This article aims to delve into the intricacies of the four primary types of variables in Java: Local, Global (or class), Instance, and Static.
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ global variable in java
Global Variable in Java - Scaler Topics
April 11, 2024 - Java being a strictly object-oriented programming language doesn't have the concept of a global variable. But by using static and final keywords, a variable can have all the functionality of a global variable.
๐ŸŒ
W3Docs
w3docs.com โ€บ java
Global variables in Java
In Java, there is no such thing ... class. However, you can create a global variable by declaring a static field in a class, and then accessing that field from anywhere in the program using the class name....
๐ŸŒ
Study.com
study.com โ€บ courses โ€บ business courses โ€บ business 104: information systems and computer applications
Java Global Variable: Declaration & Examples - Lesson | Study.com
January 7, 2018 - Since Java is object-oriented, everything is part of a class. The intent is to protect data from being changed. A static variable can be declared, which can be available to all instances of a class.
Top answer
1 of 5
12

Your main method is static, so it can access only the static fields of the class directly. Otherwise, you need to create an instance of PlannerMain first, then you can access its fields. I.e.

public static void main(String[] args){
  PlannerMain planner = new PlannerMain();
  planner.frame = new JFrame("Land Planner");
  planner.makeMap = new JButton("Make Map");
  planner.makeMap.addActionListener(new makeMapListener());
  ...
}

Note that such initialization code is better put in a constructor method.

Btw the variables you refer to are not global. Right now you have as many distinct frame and makeMap as many instances of PlannerMain you create. They would only be "global" (or its closest equivalent in Java) if you declared them public static - in this case all PlannerMain instances would share the same frame and makeMap, and the external world would see them as well.

2 of 5
6

There are no global variables in Java in the meaning of variables which would be valid in the whole program.

There are

  • class variables: These are most similar to what are called "global" variables in other languages. They are declared inside a class with the static keyword. There is only one variable for the whole class. (If the class would be loaded again with another classloader, this new class would have new variables, of course.)

    They should be used prefixed with the class: MyClass.varName. Inside of the class you also can omit the prefix, and you also could use them prefixed with an object of that type (but this is discouraged).

  • instance (or object) variables: These are what you have in your example: anything declared inside a class (and outside of any method/constructor/block) without the static keyword is a instance variable. For each object of the containing class (which includes objects of any subclasses of this class) there is exactly one variable. (From the "state" view, one could say an object consists of all its instance variables + an identity.)

    They are used prefixed by an object (of the right type): myObject.varName. Inside of non-static methods of this class you can use them unprefixed (this is then referring to the variables of the current object).

  • local variables: These are all variables declared inside of a method or a constructor (or block). They exist once for each invocation of this method, and cease to exist after the method finished. They can only be accessed from inside this method/block, not from methods called from there.

    Special cases of these are method/constructor parameters and catch-block-parameters.

  • array elements: Every element of an array is a variable of the same type. They can be used everywhere where one has a reference to this array (often in one of the other types of variables), using an index in brackets.

So, in your case you have object variables, and want to use them from a class method (static method). A class method has no current object, thus you have to qualify your variables with an object to use them. Depending on what you want, it may be useful to write it this way:

import java.awt.event.*;
import javax.swing.*;
 
public class PlannerMain {
   JFrame frame;
   JButton makeMap;
   
   void initGUI() {
     frame = new JFrame("Land Planner");
     makeMap = new JButton("Make Map");
     makeMap.addActionListener(new makeMapListener());
     frame.setSize(580,550);
     frame.setVisible(true);
   }

   public static void main(String[] args){
     PlannerMain pm = new PlannerMain();
     pm.initGUI();
   }
}
๐ŸŒ
Physics Forums
physicsforums.com โ€บ other sciences โ€บ programming and computer science
Coding in Java - replacement for a global variable โ€ข Physics Forums
February 4, 2014 - Or perhaps I am approaching it completely wrong, and that's just not the way you program in Java? ... You don't need to put the static variables in the main class. You can create a class (or classes) that only contain static variables. ... public class FooData { public static int bar = 5; } And then reference FooData.bar wherever you need it. You can declare the variable final if you want the value to be read-only. If you want to stop yourself "accidentally" referencing a global, you can put them in an interface:
๐ŸŒ
Java Guides
javaguides.net โ€บ 2023 โ€บ 12 โ€บ difference-between-global-and-static-variables-in-c.html
Difference between Global and Static Variables in C
December 17, 2023 - A global variable is accessible from any function within the same program file, while a static variable's scope is limited to the function/block in which it is declared but its lifetime extends across the entire run of the program.
Top answer
1 of 3
12
  • No class is an island.
  • There are no silver-bullets, at least its very true in programming.
  • Premature optimisation is the root of all evil.
  • In Java we don't have global variables. We only have class variables, instance variables, and method variables.

[Edit]

I am trying to explain here my last point. In fact, bringing the discussion, that is going-on in comments below, to the actual post.

First look at this, an SO thread of C#. There folks are also suggesting the same thing, which is,

  • There are no global variables in C#". A variable is always locally-scoped. The fundamental unit of code is the class, and within a class you have fields, methods, and properties
  • I would personally recommend erasing the phrase "global variable" from your vocabulary (this is in the comment section of the original question)

So, here we go.

retort: Classes are globally scoped, and thus all class variables are globally scoped. Hence should be called global.

counter-retort: Not all classes are globally scoped. A class can be package-private. Therefore, the static variables in there will not be visible outside the package. Hence, should not be called as global. Furthermore, classes can be nested, thus can be private as well and definitely can have some static variables but those wouldn't be called global.

retort: public classes are globally scoped, and thus all class variables are globally scoped.

counter-retort: Not exactly. I would like to move the previous argument here but on a variable level. No matter if the class itself is public. The variables in there can be protected, package-private and private. Hence, static variables will not be global in that case.

Now, if you like to call public static variable in public static class, as global then call it by any means. But consider this, when you create a new ClassLoader (as a child of the bootstrap ClassLoader) and load a class that you've already loaded. Then that results in a "very new copy of the class" -- complete with its own new set of statics. Very "un-global", indeed. However, we don't use the word global in Java because it tends to confuse the things and then we need to come with whole lot of explanations just to make everything clear. Folks rightly like to explain the feature of global variables in Java by static variables. There is no problem in that. If you have some problem/code in any other language and that is using global variables and you need to convert that code to Java, then you most likely make use of static variable as an alternative.

A couple of examples I like to render here

  1. When I started Java, instructors like to explain the difference of passing object type variable and primitive variables. And they constantly use the term objects are pass-by-reference, whereas primitives are pass-by-value. Students found this explanation quite confusing. So, we came up with the notion that everything in Java is pass-by-value. And we explain that for objects references are pass-by-value. It becomes much more clear and simple.

  2. Similarly, there are languages which support multiple-inheritance. But Java doesn't, again arguably speaking. But folks tend to explain that feature using interfaces. They explain it by class implementing many interfaces, and call it multiple-inheritance. That's perfectly fine. But what the class, actually, receives by inheriting a number of interfaces. Frankly speaking, nothing. Why?

    . Because all the variables in interfaces are implicitly public, final and static, which apparently means those belongs to the class and anyone can access those. Now we can say that perhaps there would be some inner class in the interface, then the class implementing the interface will have it. But again that will be static implicitly and will belong to the interface. Therefore, all what the class will get are methods. And don't forget just the definition and the contract which says, "the class implementing this interface must provide the implementation of all methods or declare itself abstract". Hence, that class will only get responsibilities and nothing much. But that solves our problems in a brilliant way.

Bottom line

Therefore, we say

  • There are no global variables in Java
  • Java doesn't support multiple-inheritance, but something like that can be achieved by implementing multiple interfaces. And that really works
  • There is nothing pass-by-reference in Java, but references are pass-by-value

Now I like to site few more places

  • Java does not support global, universally accessible variables. You can get the same sorts of effects with classes that have static variables [Ref]
  • However, extern in ObjectiveC is not an alternative to a class-scoped static variable in Java, in fact it is more like a global variable โ€ฆ so use with caution. [Ref]
  • In place of global variables as in C/C++, Java allows variables in a class to be declared static [Ref]
  • Furthermore, the overuse of static members can lead to problems similar to those experienced in languages like C and C++ that support global variables and global functions. [Ref]

All these are inferring one and the same idea. Which is Java doesn't support global variables.

Hell, I wrote that much. Sorry folks.

2 of 3
0

Performance doesn't matter. You want it as easy to read as possible.

I would do 2 as much as you can. When you really need constants and statics, make constants and statics.

For example, a null safe trim makes a good static method. New upping a StringTrimmer is silly. Putting if null then x else z in 1000 others is silly.

๐ŸŒ
Reddit
reddit.com โ€บ r/programming โ€บ why are public static final variables not considered to be global variables in java?
r/programming on Reddit: Why are public static final variables not considered to be global variables in Java?
January 12, 2020 - Can you give an example of this, "If they are pointers to objects, I think they would be considered a global variable, if and only if the object is not effectively immutable". ... public static final List<Integer> strings = new ArrayList<>(); will always be the same ArrayList, but, you can mutate it, say with strings.add("1");