String的内存分配

1、String类是final类不能被继承

2、String str="abc"的内部工作

(1)先在栈中定 一个名为str的String类的引用变量 String str;

(2)在栈中查找有没有存放值为"abc的地址",如果没有,则开辟一个存放字面值为"abc"的地址,接着创建一个新的String类的对象o,并将o的字符串值指向这个地址,而且在栈中这个地址旁边记下这个引用的对象o。如果已经有了值为"abc"的地址,则查找对象o,并返回o的地址。

(3)将str指向对象o的地址。

3、String str = new String("abc");

(1)在栈中定义String str

(2)在堆中创建对象 new String("abc")

(3)栈中的str指向堆中abc的地址

4、

static void testString(){
        String a = "helloworld";
        String b = new String("helloworld");
        String c = "hello"+"world";
        System.out.println(a==b);//false
        System.out.println(a==c);//true
        System.out.println(b==c);//false
        
        System.out.println(a.equals(b));
        System.out.println(a.equals(c));
        System.out.println(c.equals(b));
    }
原文地址:https://www.cnblogs.com/fubaizhaizhuren/p/String.html