0

I don't understand this code , please help me

String daytype= switch(day)

29th Aug 2022, 3:33 PM
wissal boussekine
wissal boussekine - avatar
4 Answers
+ 2
Incomplete code
29th Aug 2022, 3:48 PM
A͢J
A͢J - avatar
+ 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..
30th Aug 2022, 3:57 PM
Jayakrishna 🇮🇳
0
I know but I ask for why we use this statement and when
29th Aug 2022, 8:01 PM
wissal boussekine
wissal boussekine - avatar
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."; }
31st Aug 2022, 1:31 AM
Stephan Peters
Stephan Peters - avatar