1 类变量的定义
static String s1 = "aa"
类变量的引用s1是在方法区,jdk1.8就是元空间。类变量的值 "aa"是存在字符串常量池中(堆空间)
验证:
public class StaticTest {
//定义一个static修饰的变量 类变量
private static Strings1 ="aa";
public static void main(String[] args) {
StaticTest staticTest =new StaticTest();
staticTest.fun1();
}
public void fun1() {
//方法中定义一个局部变量s2,指向字符串常量池中的"aa"
String s2 ="aa";
System.out.println(s2 == StaticTest.s1); //true
}
}
总结: /结果为true。可以验证类变量(static修饰的变量)的值也是存储中堆中。
以为 String s2 ="aa";其中aa是存在字符串常量池(jdk1.8在堆空间中)。并且s2 == StaticTest.s1。两个地址一样,说明s1也是指向字符串常量池中aa这个地址。也就是类变量也是存在堆中。
同时有下面结果:
public class StaticTest {
//定义一个static修饰的变量 类变量
private static Strings1 =new String("aa");
private static Strings2 =new String("aa");
public static void main(String[] args) {
StaticTest staticTest =new StaticTest();
staticTest.fun1();
}
public void fun1() {
//方法中定义一个局部变量s2,指向字符串常量池中的"aa"
String s2 ="aa";
System.out.println(s2 == StaticTest.s1); //false
System.out.println(s1 == StaticTest.s2);//false
}
}
StaticTest.s1,StaticTest.s2两个分别在堆空间创建不同的对象。所以s1 == StaticTest.s2为fasle
String s2 ="aa";s2是字符串常量池中的对象。所以s2 == StaticTest.s1也是fasle