java foundation building-advanced understanding of the static keyword, the difference between instance variables and static variables in memory
1. JVM memory structure (5 areas)
- Heap: The instance object created by new is dynamically allocated.
- Method area: static, constant, permanent reference, static modified.
- Java stack, virtual machine stack, basic data types and object references.
- Native method stack: Native method.
- Program Counter: The location of execution.
2. Code examples
public class UserDemo {
private String name;
private String id;
private static String sex = "男";
public UserDemo(String name, String id) {
this.name = name;
this.id = id;
}
public static void main(String[] args) {
System.out.println(UserDemo.sex);
UserDemo xiaohoong = new UserDemo("xiaohoong", "111");
System.out.println(xiaohoong.id);
System.out.println(xiaohoong.name);
UserDemo xiaoming = new UserDemo("xiaoming", "222");
System.out.println(xiaoming.id);
System.out.println(xiaoming.name);
}
}
Based on this code, analyze the difference between instance variables and static variables in memory.