2

Let's see the following simplest code snippet in Java.

final public class Parsing
{
    public static void main(String[] args)
    {
        int p=10;
        int q=10;

        System.out.println(p==q);
    }
}

The above code in Java is fine and displays true as both p and q of the same type (int) contain the same value (10). Now, I want to concatenate the argument of println() so that it contains a new line escape sequence \n and the result is displayed in a new line as below.

System.out.println("\n"+p==q);

Which is not allowed at all because the expression p==q evaluates a boolean value and a boolean type in Java (not Boolean, a wrapper type) can never be converted to any other types available in Java. Therefore, the above mentioned statement is invalid and it issues a compile-time error. What is the way to get around such situations in Java?


and surprisingly, the following statements are perfectly valid in Java.

System.out.println("\n"+true);
System.out.println("\n"+false);

and displays true and false respectively. How? Why is the same thing in the statement System.out.println("\n"+p==q); not allowed?

Lion
  • 18,729
  • 22
  • 80
  • 110

5 Answers5

12

You have to add parentheses () around p==q (the way you write it, it will be interpreted as ("\n"+p) == q, and String cannot be compared to a boolean). This operator precedence is desired for expressions like

if(a+b == c+d)

etc. So,

System.out.println("\n"+(p==q));

Should work just fine.

misberner
  • 3,488
  • 20
  • 17
2

The order of precedence of operators means that your expression gets evaluated as

 ("\n" + p) == q

It is nonsensical to compare a string to an int so compilation fails, try:

 "\n" + (p == q)
Rich O'Kelly
  • 41,274
  • 9
  • 83
  • 114
2

System.out.println("\n"+p==q);

compiler treat it as

System.out.println(("\n"+p)==q); 

Use

System.out.println("\n"+(p==q)); 
Prince John Wesley
  • 62,492
  • 12
  • 87
  • 94
2

Which is not allowed at all because the expression p==q evaluates a boolean value and a boolean type in Java (not Boolean, a wrapper type) can never be converted to any other types available in Java.

This is completely wrong. Concatenating anything to a String is implemented by the compiler via String.valueOf(), which is also overloaded to accept booleans.

The reason for the compiler error is simply that + has a higher operator precedence than ==, so your code is equivalent to

System.out.println(("\n"+p)==q);

and the error occurs because you have a String and an int being compared with ==

On the other hand, this works just as intended:

System.out.println("\n"+(p==q));
Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
1

Ah. The statement is wrong.

System.out.println("\n"+(p==q));

~Dheeraj

Dheeraj Joshi
  • 3,057
  • 8
  • 38
  • 55