aspose file tools*
The moose likes Java in General and the fly likes Can u we have global variables in Java! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Can u we have global variables in Java!" Watch "Can u we have global variables in Java!" New topic
Author

Can u we have global variables in Java!

Anup kumar
Greenhorn

Joined: Dec 08, 2000
Posts: 1
Is it possible to have global variables in java.
Thanks,
Anup.
Anil Vupputuri
Ranch Hand

Joined: Oct 31, 2000
Posts: 527
Basic Singleton Class
Java does not support global variables. While purists say this is a good thing, is does present a considerable stumbling block to C++ programmers who are used to developing with them. Every variable in Java must be declared within a class. However, Java uses the static keyword to indicate that a particular variable is a class variable rather than an instance variable. What this means is that there will be only one copy of the variable for the class rather than one for each instance of the class. It will, in effect, be global within that class. There will be one and only one copy of a class variable no matter how many instances of the class are created. The static keyword enables the implementation of the Singleton class.
Here is how it would be implemented in Java:

public class Singleton
{
// methods and attributes for Singleton pattern
private Singleton() {}
static private Singleton _instance;
static public Singleton getInstance() {
if (_instance == null)
_instance = new Singleton();
return _instance;
}
// methods and attributes for global data
}
-Anil


SCJP 1.5, SCEA, ICED (287,484,486)
Anil Vupputuri
Ranch Hand

Joined: Oct 31, 2000
Posts: 527
Hi,
I found this one from one of the sites.
Implementing Global Variables
Now that the infrastructure of the Singleton class has been developed, the global data can be implemented.
Global data should be declared to be private and getter and setter methods should be used for access. Declaring the data as a private and controlling access ensures it will not be changed accidentally or maliciously from outside the class. It also allows the Singleton to enforce error checking and control access.
Using a standard naming convention for getters and setters will make the code much more understandable. Setters, methods that set the value of a variable, should use the prefix set in the method name. Getters, methods that retrieve values, should use the prefix get in the method name. Getters that retrieve a Boolean value should use the prefix is in the method name.
Examples:

setEnabled()
getName()
isEnabled()

Using this naming convention, a global integer would be implemented as seen in Listing 4.

// keep global data private
private int globalInteger;

public int getGlobalInteger() {
return globalInteger;
}

public void setGlobalInteger(int value) {
globalInteger = value;
}

Listing 4
An initGlobals() method can be used to do any required initialization of the global data at the time the Singleton is instantiated. An example of this is shown in Listing 5:

private Singleton() { // private constructor
initGlobals();
}
// methods and attributes for global data

// constructor for global variables
private void initGlobals() {
globalInteger = 5;
}

Listing 5
Accessing the globalInteger from anywhere in your Java code can then be done in the following fashion:

Singleton.getInstance().getGlobalInteger();

Listing 6
Controlling access to the global variables allows for the implementation of calculated data. For example, if there was a counter that was used to generate unique IDs, then you wouldn't want a setter method and the getter might be synchronized, as shown in this example code:

private void initGlobals() {
idCounter = 0;
}

private int idCounter;

synchronized public int getUniqueID() {
idCounter++;
return idCounter;
}

Listing 7
While the examples shown here all depict simple data being used globally, there is no reason why more complex structures can't be used as well. The Singleton class can be used to aggregate any number of objects.
Conclusion
With just a few lines of code, the Singleton pattern can be implemented in Java to provide a single point where all global data can be stored and accessed. Java is already an easy language for C++ developers to pick up, but mastering the Singleton pattern and using it to implement global data makes the transition easier than ever.

-Anil.
Atonu Bhowmik
Greenhorn

Joined: Nov 07, 2000
Posts: 9
Dear Anup,
Java does'nt support global vaiable as such. As you know all the vaiables should be defined within a class. There are 4 specifier for accessing variables , and they are :
Given below a chart showing accesing level
Specifier Class Subclass package world
-------- ----- -------- ------- -----
private X
protected X X X
public X X X X
package X X
hope the above table help you out.

regards,
Atonu Bhowmik
Frank Carver
Sheriff

Joined: Jan 07, 1999
Posts: 6920
If you really need global variables, the simplest thing to do is to put them in a class (called Global, say) and mark them as public static. Here is an example:

But bear in mind that global variables are almost always a bad thing. Global constants can be really useful (mark these as public static final), but global variables will trip you up sooner or later.


Read about me at frankcarver.me ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
Asheesh_talwar
Greenhorn

Joined: Nov 30, 2000
Posts: 12
Frank the program that U have just given have
one bug you have declared two public class's
In java in one file only class can be Public.
So it must be class Global and not public class Global.
Ajith Kallambella
Sheriff

Joined: Mar 17, 2000
Posts: 5782
Checkout how Java language itself implements global variables. Very good examples are the MIN_VALUE and MAX_VALUE for the numeric wrapper classes( Double, Integer, Long etc ) and the NEGATIVE_INFINITY, POSITIVE_INFINITY and various NaN-s.
Ajith


Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
Mark Herschberg
Sheriff

Joined: Dec 04, 2000
Posts: 6037
While the singleton patern is the right one to use for global variables (I've heard of some people using interfaces, too, but don't recommend it), I would not suggest throwing all global variables into a single class. (This starts down the path of the OO purist's argument.)
Ultmately, for any given value, there is (or should be) one class in your hierarchy which is more responsible for that value than the other clases. The use of some generic "MyConstants" class just leads to sloppy programming (to take the idea ad absurdum: why not make all fields and method public, wouldn't that be easiest?)
If you absolutely cannot think of a class in which to put a constant, at least try to break it down into package groupings, to help minimize interdependencies between system components.
As others have mentioned, these values should all be accessed with setter/getter methods, unless they have a fixed value (e.g. Pi), in which case you should declare it public static final.
--Mark
hershey@eyeshake.com
Anand Parulkar
Greenhorn

Joined: Dec 08, 2000
Posts: 1
Hi
In Java you can not directly have global variables as in PB,VB.
But you can make one public class and then declare static variable in that class.
So that variable has only one copy for that class and that variable can be accessed by any other class.(Thus we can say it is global now)

------------------
AGP


AGP
Carl Desborough
Greenhorn

Joined: May 08, 2000
Posts: 22
The static singleton pattern described above will usually work ... but one special case where it may not work is for EJBs where the container/server uses multiple JVMs.
The static variables will only be unique inside each of the JVMs so if you have non-final static variables, they may not behave in the way you expect them to when you change their values.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can u we have global variables in Java!
 
Similar Threads
global variables in Java
In java global variable are not used because
Global variables in java
Static and Global variables
Why there are no global variables in Java?