我遇到了这一行的问题(下面评论):
System.out.println("Using == ::"+s3==s4)
输出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);
}
}
Output-Using Equals Method::false Using Equals Method::true Using == ::false java Directly printing the s2 value which is autocasted from superclass to string subclass Directly printing the s1 value which is autocasted from superclass to string subclass javaDeveloper
答案 0 :(得分:33)
你错过了一组括号:
System.out.println("Using == ::" + (s3==s4));
在您的版本中,"Using == ::" + s3
正在通过==
与s4
进行比较,这不是您想要的。
一般来说,+
的{{3}}高于==
,这就是"Using == ::" + s3==s4
被评估为("Using == ::" + s3) == s4
的原因。
答案 1 :(得分:13)
您正在使用此代码:
System.out.println("Using == ::"+ s3==s4);
正在评估为:
System.out.println( ("Using == ::" + s3) == s4);
因此,您将 false 作为输出。
原因是,根据此+
表,运算符优先级==
高于Operator Precedence
:http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
正如其他答案所说,你需要使用括号括起你的布尔表达式:
System.out.println("Using == ::" + (s3==s4));
答案 2 :(得分:5)
这条线是正确的:
"Using == ::"+s3
不等于s4
您需要更改代码:
"Using == ::"+(s3==s4)
修改强> 给定代码的输出是:
Using Equals Method::false
Using Equals Method::true
false
javaDirectly printing the s2 value which is autocasted from superclass to string subclass
Directly printing the s1 value which is autocasted from superclass to string subclass javaDeveloper
Shantanu