简体   繁体   中英

Why System.out.println() doesn't print the string

public class Main {
    public static void main(String[] args) {
        String str1 = new String("Haseeb"); 
        String str2 = new String("Haseeb");
        System.out.println("str1==str2" + str1==str2  );
    }
}
  • output is "false"
  • I am expecting "str1==str2 false"

The == operator is of lower precedence than + , so + gets execute first.

"str1==str2" + str1 yields "str1==str2Haseeb" .

Then == executes, and "str1==str2Haseeb" is not the same object as "Haseeb" ( str2 ), so false is printed.

You can add parentheses to clarify the desired order of operations.

System.out.println("str1==str2 " + (str1==str2)  );

This should print str1==str2 false .

(a + b == c) evaluates as (a + b) == c , not a + (b==c) , because + has higher precedence than == . Otherwise arithmetic wouldn't work.

What you have there is equivalent to:

System.out.println( ("str1==str2" + str1) ==str2  );

And ("str1==str2" + str1) is not equal to str2 , so you print false .

What you probably mean is:

System.out.println("str1==str2 " + (str1==str2));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM