Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java Language
Expertise: Beginner
Aug 10, 1999

Global Variables

Question:
One of the things left out of Java that we had in C++ was global variables. Is there a way to use global variables in Java?

Answer:
Even though Java requires that all variables and functions must be declared within the scope of a class, it is possible to have global variables. Think of System.in and System.out for example. They are global variables accessible to all parts of an application. You can implement global variables in a Java application by declaring them as static members of a class. For an application it will sometimes make sense to declare an ApplicationGlobals class that only contains public static variables and methods intended for use throughout the entire application.

More often than not, however, the aggregation of globals into a single class can be avoided. As your application evolves, you will often find that global variables are a source of problems when adding new functionality. It is often possible to provide globally accessible instances of objects through default factory methods, such as java.awt.Toolkit.getDefaultToolkit(). It can also be a good idea to use synchronized set and get methods to access the global data in order to avoid potential conflicts between threads modifying public variables.

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date