In previous tutorial we have discussed regarding variables, so now we will look what is java global variables.
Java Global Variables :
When we have locally declared a variable and assigned a value we cannot use it any where else in the program because the same name for the variable cannot be used again.
To solve this we declare variables as global which meansĀ we declare them at the very start of the program after class
public class variables { // Global variables declaration public static void main(String args[]) { // Local variables declaration } }
Generally we declare a local variable as
int a;
with value assigned
int a = 5;
Now declare global variables as
public static int a;
with value assigned
public static int a = 5;
Here public is access specifier and static is used for constant variable.
So will see a small example of global declaration
1) int:
public class variables { public static int a = 5; public static void main(String args[]) { // integer System.out.println(a); } }
Now we can override the value assigned to int a and re assign value of a
a = 3;
public class variables { public static int a = 5; public static void main(String args[]) { // integer a = 3; System.out.println(a); } }
2) String:
Same as int we declare a String variable abc globally and we use it in our program.
public static String abc = "welcome"; public static void main(String args[]) { // String System.out.println(abc); }
3) float:
public static float value = 10.15f; public static void main(String args[]) { // float System.out.println(value); }
4) boolean:
public static boolean exam = true; public static void main(String args[]) { // boolean if (exam==true) System.out.println("pass"); else System.out.println("fail"); }
5) char:
public static char text = 'a'; public static void main(String args[]) { // char System.out.println(text); }
If any tutorials on Java Global Variables do let us know in the comment section below.
For more interesting tutorials do like and share this tutorial.