我遇到此行的问题(在下面评论):
System.out.println("Using == ::"+s3==s4)
输出false。
false
但是,System.out.println(s3==s4)输出true。
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); } } 输出使用等于方法:: false 使用等于方法:: true 使用== :: false java直接打印从超类自动转换为字符串子类的s2值 直接打印从超类自动转换为字符串子类javaDeveloper的s1值
您缺少一组括号:
System.out.println("Using == ::" + (s3==s4));
在您的版本中,"Using == ::" + s3正在通过==与进行比较s4,这不是您想要的。
"Using == ::" + s3
==
s4
通常,+的优先级高于==,这就是为什么"Using == ::" + s3==s4将其评估为的原因("Using == ::" + s3) == s4。
+
"Using == ::" + s3==s4
("Using == ::" + s3) == s4