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 OverflowGlobal variables in Java - Stack Overflow
When is it okay to declare global variables?
[Java] Why are global variables bad?
What is a work around global variables in java. I need to use a global variable for assignment, but my professor says we cant use global variable.
Your professor is telling you not to use a global variable for a reason. Why you need to add values to an array list. Design your classes and instances around that why.
Professionally, we avoid global variables because they are bad design that can have nasty side effects.
More on reddit.comVideos
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;
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.
I've been told that it's generally good practice to avoid declaring variables globally, so I always try to declare everything in the smallest scope possible.
What is the problem with global variables and when is it okay to use them? Are there any good hard-and-fast rules on the topic?