Kru*_*hna 3 java string boolean
我有以下代码
public class Test {
public static void main(String[] args) {
Integer i1=null;
String s1=null;
String s2=String.valueOf(i1);
System.out.println(s1==null+" "+s2==null);//Compilation Error
System.out.println(s1==null+" ");//No compilation Error
System.out.println(s2==null+" ");//No compilation error
}
}
Run Code Online (Sandbox Code Playgroud)
如果将两个布尔值与String组合,为什么会出现编译错误
编辑:编译错误是操作符==未定义参数类型boolean,null
这是一个优先事项.我永远不会记住我头顶的所有优先规则(我不会尝试)但我怀疑编译器试图将其解释为:
System.out.println((s1==(null+" "+s2))==null);
Run Code Online (Sandbox Code Playgroud)
......这没有意义.
目前还不清楚你对这三行中的任何一行的期望是什么,但你应该使用括号来使你的意图对编译器和读者都清楚.例如:
System.out.println((s1 == null) + " " + (s2==null));
System.out.println((s1 == null) + " ");
System.out.println((s2 == null) + " ");
Run Code Online (Sandbox Code Playgroud)
或者你可以使用局部变量使它更清晰:
boolean s1IsNull = s1 == null;
boolena s2IsNull = s2 == null;
System.out.println(s1IsNull + " " + s2IsNull);
System.out.println(s1IsNull + " ");
System.out.println(s2IsNull + " ");
Run Code Online (Sandbox Code Playgroud)