Skip to main content

Conditional Operator

  • It is ternary operator.
  • <Operand1> ? <Operand2> : <Operand3>
  • Operand1 must be of boolean type.
  • If Operand1 is true then Operand2 will be returned otherwise Operand3 will be returned.

Lab155.java

class Lab155 {

public static void main(String[] args) {
int a = true ? 10 : 20;
int b = false ? 10 : 20;

System.out.println(a);
System.out.println(b);
}
}

Lab156.java

class Lab156 {

public static void main(String[] args) {
int a = 20 > 10 ? 10 : 20.0;
double d = 20 > 10 ? 10 : 20.0;
int x = 10 > 20 ? 10 : "TWENTY";
String str = 10 > 20 ? 10 : "TWENTY";
}
}

Lab157.java

class Lab157 {

public static void main(String[] args) {
Object obj = 10 > 20 ? 10 : "TWENTY";

System.out.println(obj);
}
}

Lab158.java

class Lab158 {

public static void main(String[] args) {
int a = 10;
int b = 20;

int max = a > b ? a : b;
System.out.println(max);

int min = a < b ? a : b;
System.out.println(min);
}
}

Lab159.java

class Lab159 {

public static void main(String[] args) {
int a = 10;
int b = 23;
int c = 12;

int max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);

System.out.println(max);
}
}