String文字的行为在下面的代码中非常混乱.
我可以理解第1行,第2行和第3行true,但为什么是第4行false?
当我打印两者的哈希码时,它们是相同的.
class Hello
{
public static void main(String[] args)
{
String hello = "Hello", lo = "lo";
System.out.print((Other1.hello == hello) + " "); //line 1
System.out.print((Other1.hello == "Hello") + " "); //line 2
System.out.print((hello == ("Hel"+"lo")) + " "); //line 3
System.out.print((hello == ("Hel"+lo)) + " "); //line 4
System.out.println(hello == ("Hel"+lo).intern()); //line 5
System.out.println(("Hel"+lo).hashCode()); //hashcode is 69609650 (machine depedent)
System.out.println("Hello".hashCode()); //hashcode is same WHY ??.
}
}
class Other1 { static String hello …Run Code Online (Sandbox Code Playgroud) 我正面临着这条线的问题(下面评论):
System.out.println("Using == ::"+s3==s4)
Run Code Online (Sandbox Code Playgroud)
哪个输出false.
但是,System.out.println(s3==s4)产出true.
现在,我无法理解为什么我得到这个结果:
public class string {
public static void main(String[] args){
String s3="Shantanu";
String s4=s3;
String s1=new String("java");
String s2=new String("javaDeveloper");
System.out.println("Using Equals Method::"+s1.equals(s2));
System.out.println("Using Equals Method::"+s3.equals(s4));
System.out.println("Using == ::"+s3==s4);//Problem is here in this line
System.out.println(s1+"Directly printing the s2 value which is autocasted from superclass to string subclass ");
System.out.println("Directly printing the s1 value which is autocasted from superclass to string subclass "+s2);
System.out.println(s3);
}
}
Run Code Online (Sandbox Code Playgroud)
Output-Using Equals Method::false …