-1

I have a below code :

boolean prime = true;
System.out.println("Number is"+ prime ? "prime" : "not prime" );

The above code is giving compile time error. When i modify it to :

System.out.println("Number is"+ prime==true ? "prime" : "not prime" );

It says that "Incompatible operand type : String and Boolean". When I modify it as

System.out.println(prime? "prime" : "not prime" );

OR

System.out.println(prime==true? "prime" : "not prime" );

It works perfectly. What is the reason behind this behavior. Does it treat prime as a String object in Sysout? When I am using any other string in Sysout it doesnot work properly.

AalekhG
  • 361
  • 3
  • 8

1 Answers1

1

Look at operator precedence:

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html

System.out.println("Number is"+ (prime ? "prime" : "not prime") );

Ternary operator has one of the lowest precedence, so it will behave in your case as follows:

System.out.println(("Number is"+ prime) ? "prime" : "not prime" );

This is surely not what you want

maskacovnik
  • 3,080
  • 5
  • 20
  • 26