1 類變量的定義
static String s1 = "aa"
類變量的引用s1是在方法區(qū),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兩個分別在堆空間創(chuàng)建不同的對象减俏。所以s1 == StaticTest.s2為fasle
?String s2 ="aa";s2是字符串常量池中的對象。所以s2 == StaticTest.s1也是fasle