String直接賦值和new物件的區別

2021-09-25 23:17:27 字數 823 閱讀 7698

string直接賦值和new物件的區別

string s = "hello world";

string s = new string("hello world");

首先string s = 「hello world"是賦值語句,它會先在常量池查詢是否有這個值,如果有,就將這個位址賦值給s,如果沒有就在常量池開一塊空間給hello world 然後賦位址給s。new string(「hello world」) 也一樣,會先在常量池尋找是否存在"hello world」,如果存在,直接將它賦給在堆中建立的物件。這裡還涉及另外乙個比較需要注意的點,也就是string s = new string(「hello world」)這句**一共建立多少個物件,通過前面的描述我們可以知道答案是乙個或者兩個,當常量池中存在"hello world"是只要在堆中建立乙個物件即可,當常量池中沒有"hello world"時,在常量池中需要建立乙個物件,在堆中也要建立乙個物件。

public class test

}

**輸出的結果是

true

false

true

false

false

為什麼在輸出語句中system.out.println(s1==ss);的結果會是false呢?s1不是在常量池找到「hello world」然後就拿來用了嗎?答案是,system.out.println(s1==ss);比較的是兩個變數的值,變數s1和變數ss,而變數s1指向的是堆中對應的物件,變數ss指向的是常量池中的物件,自然false了。

String直接賦值和使用new的區別

string str2 new string abc 上面語句建立了幾個字串物件?上面語句實際上建立了2個字串物件,乙個是 abc 這個直接量對應的物件,乙個是new string 構造器返回的字串物件。在jvm裡,考慮到垃圾 garbage collection 的方便,將heap 堆 劃分為三部...

String直接賦值和new乙個物件的理解

我們直接來看兩句 string str1 new string abc string str2 abc system.out.println str1 str2 輸出false 首先,既然有new這個關鍵字,那麼一定要在堆記憶體中開闢空間,存放資料。所以 str1 指向的是堆記憶體中的一片區域,而s...

委託型別定義時new和直接賦值兩種方式

public int delegate delegatefunc int a,int b public int addfunction int a,int b console.writeline a b delegatefunc functionde new delegatefunc addfunc...