-1

Possible Duplicates:
Why are there no global variables in Java?
Global variables in Java

Hi,

Is there any way to declare global Variables in java? or something with a wide scope like them? can anybody explain me why are global variables considered bad? any articles about this are really appreciated.

thank you

Community
  • 1
  • 1
user718238
  • 11
  • 1
  • 3
  • 4
    Did you search a little? You're not the first to ask [why global variables are bad](http://www.google.ca/search?q=global+variable+are+bad) nor [how to use global variables in Java](http://www.google.ca/search?q=java+global+variable). – zneak Apr 21 '11 at 03:44
  • 1
    Search before you ask! http://stackoverflow.com/search?q=global+variables+java – Laurent Pireyn Apr 21 '11 at 03:45
  • (1) `public static`, (2) because anyone can play with them. You loose control, (3) If have to, use `public static final`. – Nishant Apr 21 '11 at 03:46

4 Answers4

1

On any class, you can declare static variables:

class MyClass {

    public static String MyString = "Some String";

    ...
}

And then reference them via:

MyClass.MyString;
Sean Adkinson
  • 8,425
  • 3
  • 45
  • 64
0

You can create 'global' variables by declaring them within the scope of the class ie

public class Example {
    String globalString = "this is global";
    public static void main(String[] args){
       String localString = "this is a local variable";
    }
}

You can also create static variables which can be accessed by a method which has been declared static too.

AlanFoster
  • 8,156
  • 5
  • 35
  • 52
  • Its not global, as it can not be accessed outside the package. Even if you make that `public`, that will not make it a global variable whatsoever. – Adeel Ansari Apr 21 '11 at 03:54
  • If you look at my last line, I say about static variables... – AlanFoster Apr 21 '11 at 08:38
  • @user551841: Even `static` will not make that global, because we don't have "global" in Java. Please read the link, I provided. Its worth it. – Adeel Ansari Apr 21 '11 at 11:14
0

A good discussion can be found here, Static Methods or Not? Global variables?

Community
  • 1
  • 1
Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133
0

public static will give enough scope to your variable for them to act as global variable. But think twice before doing so.

kdabir
  • 9,623
  • 3
  • 43
  • 45