Home >Java >javaTutorial >An in-depth exploration of JVM memory layout and functions
In-depth understanding of JVM memory structure and function requires specific code examples
public class Person { private String name; private int age; // 构造方法 public Person(String name, int age) { this.name = name; this.age = age; } // Getter和Setter方法 // ... public static void main(String[] args) { Person person = new Person("Alice", 20); System.out.println(person.getName()); // 输出 "Alice" } }
In the above sample code, we create a Person object and assign values to its name and age attributes. This Person object will be allocated in heap memory. The size of the heap memory can be adjusted through the -Xmx and -Xms command line parameters.
public class StackExample { public static void main(String[] args) { int a = 5; int b = 10; int c = 0; c = add(a, b); System.out.println(c); // 输出 "15" } public static int add(int x, int y) { return x + y; } }
In the above sample code, we defined three local variables a, b and c in the main method and assigned values to them respectively. Then we called the add method and passed a and b as parameters to the add method. The parameters x and y in the add method are also local variables. In the add method, we add x and y and return the result. Finally, we output the value of c, which is 15, in the main method.
As you can see, the stack is mainly used for method calls and the storage of local variables. Whenever you enter a method, the JVM will automatically allocate a stack frame space for the method to store the method parameters and local variables. When the method completes execution, the stack frame will be destroyed.
public class MethodAreaExample { private static final String CONSTANT = "Hello, world!"; private static int count = 0; public static void main(String[] args) { System.out.println(CONSTANT); // 输出 "Hello, world!" System.out.println(count); // 输出 "0" count++; System.out.println(count); // 输出 "1" } }
In the above sample code, we define a constant CONSTANT and a static variable count. Constants and static variables are stored in the method area. In the main method, we output the values of constants and static variables respectively, and add 1 to the value of count before outputting it.
The above is the detailed content of An in-depth exploration of JVM memory layout and functions. For more information, please follow other related articles on the PHP Chinese website!