pandagrammer
pandagrammer

Reputation: 871

Using question mark if condition in print statement

I want to print a sentence like:

   boolean someSetting = true; 
   System.out.println("Running experiment " + (someSetting)? "on" : "off");

Obviously this won't compile. Is there any other suggestion to do this?

Upvotes: 2

Views: 660

Answers (2)

Jigar Joshi
Jigar Joshi

Reputation: 240966

add brackets around it to evaluate that expression to String value

System.out.println("Running experiment " + ((someSetting)? "on" : "off"));

without brackets it tries to contact (+) String and boolean and puts it as a conditional expression which is invalid

Upvotes: 7

Eran
Eran

Reputation: 394126

That's easy enough to fix:

boolean someSetting = true; 
System.out.println("Running experiment " + ((someSetting)? "on" : "off"));

Upvotes: 3

Related Questions