Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

java - Getting strange output when printing result of a string comparison

I am facing a problem with this line (commented below):

System.out.println("Using == ::"+s3==s4)

which outputs false.

However, System.out.println(s3==s4) outputs true.

Now, I am not able to understand why I am getting this result:

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
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're missing a set of brackets:

System.out.println("Using == ::" + (s3==s4));

In your version, "Using == ::" + s3 is being compared via == to s4, which isn't what you want.

In general, + has a higher precedence than ==, which is why "Using == ::" + s3==s4 is being evaluated as ("Using == ::" + s3) == s4.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...