xxxxxxxxxx
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"
xxxxxxxxxx
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"
xxxxxxxxxx
switch(x){
case(0): //if x == 0
//do some stuff
break;
//add more cases
default: //when x does not match any case
//do some stuff
break;
}
xxxxxxxxxx
public class Main {
public static String whoLikesIt(String names) {
//if names.length 4 or more it case 4
return switch (names.length >= 4 ? 4 : names.length) {
case 1 -> names[0] + " like this";
case 2 -> names[0] + " and " + names[1] + " like this";
case 3 -> names[0] + ", " + names[1] + " and " + names[2] + " like this";
case 4 -> names[0] + ", " + names[1] + " and " + (names.length-2) + " others like this";
default -> "no one likes this";
};
}
public static void main(String[] args) {
String[] arr = { "Alex", "Jacob", "Mark", "Max"};
System.out.println(whoLikesIt(arr));
}
}
xxxxxxxxxx
int dayOfWeek = 1; // Assuming 1 represents Monday
String dayName;
switch (dayOfWeek) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
System.out.println("Day of the week: " + dayName);
xxxxxxxxxx
int age = 9;
switch(age){
case 1:
System.out.println("You are 1 year old");
case 5:
System.out.println("You are 5 years old");
case 9:
System.out.println("You are 9 years old");
default:
System.out.println("Ain't know how many years you are");
xxxxxxxxxx
//the cooler looking edition (with input example)
Scanner scn = new Scanner(System.in);
int asd = scn.nextInt();
switch(asd)
{
case 1 -> System.out.println("case 1");
case 2 -> System.out.println("case 2");
case 5 -> System.out.println("case 5");
//case n...
default -> case 1 -> System.out.println("check out tunalad.bandcamp.com");
}
/* Output:
asd = 1: "case 1"
asd = 2: "case 2"
asd = 5: "case 5"
asd = 33213: "check out tunalad.bandcamp.com"
*/
xxxxxxxxxx
int x = 5;
switch(x) {
case 1:
System.out.println("You entered 1");
break;
case 2:
System.out.println("You entered 2");
break;
default:
System.out.println("You entered: "+x);
}
xxxxxxxxxx
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
default:
// default statements
}
xxxxxxxxxx
switch (/*Variable*/)
{
case /*Variable*/:
/*Action*/;
break;
default:
/*Action*/;
}