Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 283
pandagrammer Avatar asked Aug 03 '26 23:08

pandagrammer


1 Answers

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

like image 105
jmj Avatar answered Aug 06 '26 13:08

jmj



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!