How can I create a Global variable in Java? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 10

How can I create a Global variable in Java?

Iam a java beginner and still learning the basics but get stuck with the scope of variable.

30th Dec 2017, 1:08 PM
Victor
Victor - avatar
2 Answers
+ 12
Java doesn't technically support global variables. As a pure object-oriented language, everything needs to be part of a class. The reason is to protect data and members of classes from being changed (inadvertently or on purpose) by other parts of the program. However, you still may need to have variables that can be accessed across your program, and not confined to specific classes. 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;
30th Dec 2017, 1:21 PM
GAWEN STEASY
GAWEN STEASY - avatar
- 1
I want to job in java and c++
1st Jan 2018, 2:37 AM
SO sorry
SO sorry - avatar