在println()中==的功能 [英] Function of == in println()

查看:85
本文介绍了在println()中==的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String literal1 = "java"; 
String object = new String("java"); 
String literal2 = "java";

System.out.println("result 1 = " + (literal1 == object) ); 
System.out.println("result 2 = " + literal1.equals(object)); 
System.out.println("result 3 = " + literal1 == object); 
System.out.println("result 4 = " + literal1.equals(object));
System.out.println("result 5 = " + literal1 == literal2); 
System.out.println("result 6 = " + literal1.equals(literal2));





预期输出

结果1 =错误

结果2 =真实

结果3 =假

结果4 =真实

结果5 =错误

结果6 =真实



获得的输出

结果1 = false

结果2 =真实



结果4 =真实



结果6 =真



我的尝试:





Expected output
result 1 = false
result 2 = true
result 3 = false
result 4 = true
result 5 = false
result 6 = true

output obtained
result 1 = false
result 2 = true
false
result 4 = true
false
result 6 = true

What I have tried:

When this line
System.out.println("result 5 = " + literal1 == literal2);
is changed to
System.out.println("result 5 = " + (literal1 == literal2));





输出

结果5 =真实

有谁可以解释为什么会发生这种情况?



Output
result 5 = true
Could anyone please explain why this is happening?

推荐答案

首先进行添加,因此将两个字符串连接(加在一起)的结果与最后一个值进行比较。由于字符串不匹配,打印的结果将为false。添加括号意味着将在将结果添加到文字字符串之前执行相等性测试。在Java文档中查找运算符优先级以获取完整的详细信息。
The addition is happening first, so the result of the two strings concatenated (added together) is compared to the last value. The result printed will be false since the strings do not match. Adding the parentheses means that the equality test will be performed before its result is added to the literal string. Look up operator precedence in the Java documentation for full details.


)
System.out.println("result 1 = " + (literal1 == object) ); //adding paranthesis here basically forces Java to first execute literal1==object, which is true/false

System.out.println("result 2 = " + literal1.equals(object)); //it has pretty much the same effect as above, so literal.equals(object) gets executed first 

System.out.println("result 3 = " + literal1 == object); //in this case the String "result 3 =" is added with literal1 then an equality is made with "object", so obviously the output is slightly different

System.out.println("result 4 = " + literal1.equals(object)); // it`s the case of line 2, so self explanatory

System.out.println("result 5 = " + literal1 == literal2);  //it`s the case of line 3 of code

System.out.println("result 6 = " + literal1.equals(literal2)); //it`s the case of line 2 of code





底线是:

1。如果你在JAVA中调用了一些函数,比如literal1.equals(object),它将首先被执行;

2.如果你有像(expr)这样的paranthesis表达式,你将首先执行表达,然后是其余的;



The bottom line is:
1. If you have some function being called in JAVA, like literal1.equals(object), it will get executed first;
2. If you have a paranthesis expression like (expr), you will first execute that expression, then the rest;


这篇关于在println()中==的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆