String位置解析

string不是基本数据类型,那么一个string的内存位置是什么呢?一共有两种情况:

1、string直接赋值:

String s = “String”;

s的引用存在栈内存中,引用指向的String存在方法区的常量池中(先判断常量池中是否有一个haha,存在则直接指向)

2、string对象new创建

String s = new String(“String”);

s的引用存在于栈内存中,引用指向的String对象,存在堆内存中(每new一次,在堆中创建一个新的String对象)

总结:

1、string类型的引用,都是存在栈内存中的;

2、string引用指向,直接赋值存在栈内存,new出来的存在堆内存。

猜你喜欢

转载自blog.csdn.net/weixin_39443483/article/details/114972786