Question:
How to write this if else statement in 1 line?
if(i1==i2){ b1 = true; } else { b1 = false; }
Answer:
Using the ternary operator.
result = condition ? value1 : value2;
Code:
public class Example { public static void main(String args[]){ int i1=0; int i2=1; boolean b1; boolean b2; if(i1==i2){ b1 = true; } else { b1 = false; } System.out.println("b1:" + b1); // one liner b2= ( (i1==i2) ? true : false ); System.out.println("b2:" + b2); } }
Output:
$ java Example b1:false b2:false