0

According to this post Global variables in Java it describes how to define a global variables in java by using static

 public class Example {
        public static int a;
        public static int b;
    }

But at same time in other post Why are there no global variables in Java? this question contradicts . So my question is what exactly is global variable ? Do java supports global variables ?if yes ,how? if no ,why? and how java global variables(if there are any) are different from c++ global variables?

Community
  • 1
  • 1
user3690061
  • 118
  • 1
  • 3
  • 15

3 Answers3

3

I think that we can argue that there is no global keyword in java but your example can be treated like a global.

In most languages where you can define a global variable the problem is that they pollute the global namespace and name clashes can occur (like in php). In this regard there are no globals in java since there is no global namespace: variables are always in a class.

So the main thing is: there is no explicit globan in java and there is no globan namespace in java. This frees you from name clashes and accidental overwrites which is a good thing.

But there is nothing stopping you from creating a Global class with a lot of public static fields in it.

Please note that most guys (including me) would break both of your hands for doing so. :)

Adam Arold
  • 29,285
  • 22
  • 112
  • 207
0

a gloabal variable is used by many functions without need to enter it in the input of these functions. Expert advice to don't use them.

ktaria
  • 423
  • 6
  • 16
0

A global variable is a variable which can be accessed from anywhere (from any part of the program). Thus a public static variable in any Java class is global.

peter.petrov
  • 38,363
  • 16
  • 94
  • 159