Java: Switch()

Instead of writing many  statements, you can use the  statement.

if..else
switch
int day = 4;
switch (day) { // every case will be a posibility of "day"
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:
    System.out.println("Wednesday");
    break;
  case 4:
    System.out.println("Thursday");
    break;
  case 5:
    System.out.println("Friday");
    break;
  case 6:
    System.out.println("Saturday");
    break;
  case 7:
    System.out.println("Sunday");
    break;
}
// Outputs "Thursday" (day 4)
int day = 4;
switch (day) {
  case 6:
    System.out.println("Today is Saturday");
    break;
  case 7:
    System.out.println("Today is Sunday");
    break;
  default:
    System.out.println("Looking forward to the Weekend");
}
// Outputs "Looking forward to the Weekend"

Without “break”

int day = 6;
switch (day) {
  case 6:
    System.out.println("Today is Saturday");
  case 7:
    System.out.println("Today is Sunday");
  default:
    System.out.println("Looking forward to the Weekend");
}
// Outputs 
"Today is Saturday"
"Today is Sunday"
"Looking forward to the Weekend"
————————

Instead of writing many  statements, you can use the  statement.

if..else
switch
int day = 4;
switch (day) { // every case will be a posibility of "day"
  case 1:
    System.out.println("Monday");
    break;
  case 2:
    System.out.println("Tuesday");
    break;
  case 3:
    System.out.println("Wednesday");
    break;
  case 4:
    System.out.println("Thursday");
    break;
  case 5:
    System.out.println("Friday");
    break;
  case 6:
    System.out.println("Saturday");
    break;
  case 7:
    System.out.println("Sunday");
    break;
}
// Outputs "Thursday" (day 4)
int day = 4;
switch (day) {
  case 6:
    System.out.println("Today is Saturday");
    break;
  case 7:
    System.out.println("Today is Sunday");
    break;
  default:
    System.out.println("Looking forward to the Weekend");
}
// Outputs "Looking forward to the Weekend"

Without “break”

int day = 6;
switch (day) {
  case 6:
    System.out.println("Today is Saturday");
  case 7:
    System.out.println("Today is Sunday");
  default:
    System.out.println("Looking forward to the Weekend");
}
// Outputs 
"Today is Saturday"
"Today is Sunday"
"Looking forward to the Weekend"