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是否指向同一个对象

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页