super easy question about string compare(50分)

  • 主题发起人 主题发起人 蝙蝠
  • 开始时间 开始时间

蝙蝠

Unregistered / Unconfirmed
GUEST, unregistred user!
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?Wheredo
es 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));
}
}
 
首先可以知道的是==操作是引用比较
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是引用同一个实例
 
System.out.println("string1 equal string2 is:"+(string1.equals(string2)));
 
字符串比较应该用String的equals方法,用== 只是比较两个引用string1和string2是否指向同一个对象
 
I am learning...
 
接受答案了.
 
后退
顶部