There are three types of variables in Java: class variables, member variables, and local variables. They are stored separately in the JVM’s method area, heap memory, and stack memory.
Public class Variables {** ** private static int a; /** * private int b; /** * @param c */ public void test(int c){int d; }}Copy the code
Of the three variables defined above:
Variable A is the class variable, stored in the method area and shared by threads.
Variable B is a member variable that is stored in heap memory along with the object and shared by threads.
Variables C and D are local variables, stored in stack memory, exclusive to the thread.
That is, variables A and B are shared variables, and variables C and D are not shared variables.
That is, local variables are non-shared variables, scoped only inside the method, and do not escape outside the method.
So, since it is a variable whose scope is only in the method, there is no need to consider so much, how to define how high performance, how easy to use how to define.
We all know that in the Java language, new objects are stored in the heap, and we use those objects by reference in the stack; So, objects themselves are resource-intensive.
For frequently used types such as int, it would be cumbersome if we needed to new a Java object every time we used such a variable.
So, like C++, Java provides basic data types whose variables do not need to be created using new. They are not created on the heap, but stored directly in stack memory, so it is more efficient.
Welcome to the public number: programmer interview scene