0
I don't understand this code , please help me
String daytype= switch(day)
4 Answers
+ 2
Incomplete code
+ 1
Java 12 introduced new feature that you can use switch as normal expression which return a single value.
An example way I used in this code:
int start = switch(season) {
case "W" -> 1;
case "V" -> 4;
case "S" -> 7;
case "F" -> 10;
default -> 0;
};
in this example : 'start' gets assigned a value depending upon season value..
https://code.sololearn.com/cUhWk7vED7ak/?ref=app
hope it helps..
0
I know but I ask for why we use this statement and when
0
This is an example of how you would use it in Java 14 or higher:
String daytype= switch(day) {
case "monday", "tuesday", "wednesday", "thursday", "friday" -> "Weekday";
case "saturday", "sunday" -> "Weekend";
default -> "Invalid day";
};
You would use it to avoid bulky code like this:
if (day.equals("monday") {
daytype = "Weekday";
} else if (day.equals("tuesday") {
daytype = "Weekday";
} else if (day.equals("wednesday") {
daytype = "Weekday";
} else if (day.equals("thursday") {
daytype = "Weekday";
} else if (day.equals("friday") {
daytype = "Weekday";
} else if (day.equals("saturday") {
daytype = "Weekend";
} else if (day.equals("sunday") {
daytype = "Weekend";
} else {
daytype = "Invalid day.";
}