精 (String)字串拼接記憶體解析

2021-10-04 22:53:32 字數 1265 閱讀 1486

string str1 = 「hello」;

字串常量池中沒有"hello",則建立乙個字串並把位址值返回給str1

string str2 = 「hello」;

字串常量池中存在"hello",則創將該字串的位址值返回給str2

string str3 = new string( 「hello」);

str3指向物件的位址,物件中的值指向字串常量池中已有的字串

直接拼接成"helloworld",字串常量池中沒有"helloworld",則在字串常量池中建立乙個字串並把位址值返回給str4

字串常量池中沒有"world",則建立乙個字串並把位址值返回給str5

string str6 = str1 + str5;

拼接好後,字串常量池中有"helloworld",str6產生的物件的內容指向字串常量池中"helloworld"的位址

person p1 = new person(「張三」,18);

person p2 = new person(「張三」,20);

常量池中不會存在相同內容的常量。

常量與常量的拼接結果在常量池(例:string str4 = 「hello」 + 「world」;)。

只要兩個拼接中只要有乙個是變數(例:string str2 = str1 + 「aa」;),str2指向堆中的物件,物件的value指向字串常量池的字串

如果拼接的結果呼叫intern()方法,直接返回常量池中的位址

String字串拼接陷阱

先看如下程式 對於一般類物件 public class a public class test public static void main string args 再看如下程式 public class test public static void main string args 輸出的結果...

String字串拼接速率

在for迴圈中,比較常用的字串拼接方式包括以下五種方式 string,string.concat apache.commons.lang3.stringutils.join stringbuffer stringbuilder 接下來,依次分析上述五種方式 string,public final s...

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...