Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the compilation error for boolean and String

I have the below code

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
  }
}

Why there is compilation error if combine two Boolean with String

EDIT: The compilation Error is The operator == is undefined for the argument type(s) boolean, null

like image 980
Krushna Avatar asked Jan 24 '26 01:01

Krushna


2 Answers

It's a matter of precedence. I can never remember all the precedence rules off the top of my head (and I don't try to) but I suspect the compiler is trying to interpret this as:

System.out.println((s1==(null+" "+s2))==null);

... and that doesn't make sense.

It's not clear what you're expecting any of those three lines to do, but you should use brackets to make your intentions clear to both the compiler and the reader. For example:

System.out.println((s1 == null) + " " + (s2==null));
System.out.println((s1 == null) + " ");
System.out.println((s2 == null) + " ");

Or you could make it clearer using local variables:

boolean s1IsNull = s1 == null;
boolena s2IsNull = s2 == null;

System.out.println(s1IsNull + " " + s2IsNull);
System.out.println(s1IsNull + " ");
System.out.println(s2IsNull + " ");
like image 166
Jon Skeet Avatar answered Jan 25 '26 16:01

Jon Skeet


+ gets processed before ==.

This leads to s1 == " " == null

like image 30
Menno Avatar answered Jan 25 '26 15:01

Menno



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!