How to define global variables in Java?
In Java, global variables can be defined at the top of a class using the keyword static, which means outside of the class but not within methods. Global variables must be declared within a class, but cannot be declared within a method. For example:
public class GlobalVariables {
// 全局变量
public static int globalVar1 = 10;
public static String globalVar2 = "Hello";
public static void main(String[] args) {
// 访问全局变量
System.out.println(globalVar1);
System.out.println(globalVar2);
}
}
In the example above, globalVar1 and globalVar2 are global variables that can be directly accessed and used in the main method.