建立string物件,我們可以用兩種方式:
1, string s = new string("victory");
2, string s = "victory";
那麼這兩種方式的區別是?先看乙個程式:
string s1,s2;
s1=new string("we are students");
s2=new string("we are students");
string s3,s4;
s3="how are you";
s4="how are you";
此程式中 s1 s2引用不同的實體
s3 s4是引用同乙個實體
為什麼會不同呢?
------>>實際上string 型別的值是放在乙個字串常量池裡,s3="how are you"; s4="how are you";當s3執行完了後池裡有乙個物件,內容就是"how are you",再執行s4 的話,jvm首先會去池中找,當在池中找到"how are you"的話,s4直接引用它,若沒找到,在建立新的物件引用.
s1=new string("we are students"); s2=new string("we are students");棧中的s1,s2分別引用堆中兩個物件,堆中的這兩個物件指向常量池中的同乙個常量"we are students",所以s1,s2的並不相等.
現在我們回過頭來分析一下剛才的兩種不同建立string物件的方式
;1, string s = new string("victory"); //建立了兩個物件,乙個是s,乙個是victory
2, string s = "victory"; //建立了乙個物件 s ,而victory已經存在了,不用再建立,直接引用!!
String建立物件的兩種方式
用string建立物件有兩種方式 第一種為直接賦值,string 物件名 字串 例如 string name tom 第二種為new構造方法,string 物件名 new string 字串 例如string name new string tom public class test 執行結果為tu...
String類物件的兩種建立方式及不同
第一種方式是直接賦值,像如下 public class home 但這種建立方式有乙個特點就是賦的字串被存放到了堆中的乙個叫常量池的地方,它特殊就特殊在,當jvm建立字串物件前,會先去常量池中找有沒有乙個字串內容與當前字串相同。如果有,直接將已有的位址賦值給變數 如果沒有,建立新的字串,也就是說上面...
String中兩種物件例項化方法的區別
string stra zhangsan string strb zhangsan system.out.println stra strb true string str1 newstring zhangsan string str2 newstring zhangsan system.out.p...