Java字符串的比較(收藏)

This is a question about String compare.The result is different if generate string with different way--one is using keyword "new",another isn't.Please help me answer:Why did this happen?What difference between these two way?Where does the string object store?Stack or heap?on the other hand,please correct my language error.
  This is my program:
public class CompareString
{public static void main(String[] args)
 {String string1=new String("good");
  String string2=new String("good");//first way,generate string with "new",answer is "false".
  //String string1="good";
  //String string2="good";//second way,generate string without "new",answer is "true".
  System.out.println("string1 equal string2 is:"+(string1==string2));
 }
}
freedomRen (2004-01-26 18:14:00)

首先可以知道的是==操作是引用比較
String string1=new String("good");
String string2=new String("good");
new 操作創建了新的字符串對象並初始化爲good,string1,string2分別引用了各自的實例
因此引用比較結果爲false

String string1="good";
String string2="good";
Java中的字符串常量存在constant poll中標記爲CONSTANT_String,
爲了解析標記爲CONSTANT_String的常數池表項,當JVM載入.class文件,處理字符串變量時要進行常數池解析constant poll resolution的操作。如果表示相同序列的Unicode字符的另一個常數池已經被解析,那麼解析的結果是對已有的那個常量池表項的String實例的引用,也就是說此時string1,string2是引用同一個實例

wen00000000 (2004-01-27 1:17:00)

System.out.println("string1 equal string2 is:"+(string1.equals(string2)));

sunruijia (2004-02-11 15:09:46)

字符串比較應該用String的equals方法,用== 只是比較兩個引用string1和string2是否指向同一個對象

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章