Home >Java >javaTutorial >A brief discussion on how to define global variables in Java development
Any variables or codes in the program are automatically allocated memory for storage by the system during compilation, and the so-called static This means that the memory allocated after compilation will always exist, and the memory space will not be released until the program exits.
static is the static modifier. Members modified by static are allocated a memory space by the system during compilation and will not be released until the program stops running. That means that all objects of this class will share this memory space.
import java.util.*; public class Main{ static int ans;//定义全局变量 public static void main(String[] args){ Scanner scan = new Scanner(System.in); int n; while(scan.hasNext()){ ans = 0; n = scan.nextInt(); System.out.println(fib(n)+"\n递归调用了"+ans+"次"); } } private static int fib(int n){ ans ++; if(n == 1 || n == 2) return 1; return fib(n-1)+fib(n-2); } }
The above is the detailed content of A brief discussion on how to define global variables in Java development. For more information, please follow other related articles on the PHP Chinese website!