Krushna
Krushna

Reputation: 6050

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

Upvotes: 3

Views: 230

Answers (2)

Menno
Menno

Reputation: 12621

+ gets processed before ==.

This leads to s1 == " " == null

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1500175

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 + " ");

Upvotes: 6

Related Questions