String字串的儲存原理

2021-10-19 10:25:34 字數 960 閱讀 4746

string s1 =

"abc"

;string s2 =

"def"

+" gh"

;

這兩行**表示在底層建立了三個字串物件,都在字串常量池中。

string s3 =

newstring

("xy"

);

這是使用new的方式建立的字串物件,凡是雙引號括起來的都在字串常量池中有乙份。

new物件的時候一定在堆記憶體中開闢空間。

user user =

newuser

(110

,"張三"

)

儲存原理:

string s1 =

"hello"

;//hello儲存在方法區的字串常量池中

string s2 =

"hello"

;system.out.

println

(s1 == s2)

;//結果為true

string x =

newstring

("xyz");

string y =

newstring

("xyz");

system.out.

println

(x == y)

;//結果為false

==比較的是記憶體位址

字串的內部儲存原理

字串是乙個字面量,它的值儲存在常量池中 也就是方法區的執行時常量池 他的底層是使用字元陣列來儲存,它是可以共享的。以下展示直接字串與字串物件的儲存。其中string s1 ab 會產生乙個物件,也就是它底層的字元陣列。單獨的string s2 new string ab 是會產生兩個物件的,也就是堆...

String 型別字串儲存和拼接

string str1 hello string str2 he llo string str3 he new string llo str1 str2 true str1 str3 false 這個問題我試著回答一下,同時也是相互學習。string str1 hello stringstr2 he...

String的拼接字串的底層實現原理

下面 public class test1 public string tostring 可以發現 stringbuilder物件的tostring方法中是新new了乙個string物件,所以str4是指向乙個使用new新建立出來的乙個物件,不會復用常量池中的物件 所以str3的位址是和str4的位...