Java Conditionals

Ternary operator

int a = 10;
int b = 20;
int max = (a > b) ? a : b;
// Outputs: 20
System.out.println(max);

Switch

int month = 3;
String str;
switch (month) {
  case 1:
    str = "January";
    break;
  case 2:
    str = "February";
    break;
  case 3:
    str = "March";
    break;
  default:
    str = "Some other month";
    break;
}
// Outputs: Result March
System.out.println("Result " + str);

If else

int k = 15;
if (k > 20) {
  System.out.println(1);
} else if (k > 10) {
  System.out.println(2);
} else {
  System.out.println(3);
}
Comments