Switch statement |
Java does not have an equivalent of the match statement. The closest to it is the switch statement, but it is much more restricted and is very error prone. The switch is similar to the match statement in Grace in that an expression is evaluated and a different branch is executed depending on the value. However the expression must evaluate to an int or char. Here is a simple example of its use:
String dayToString(int day) { String dayName switch(day) { case 1: dayName = "Sunday"; break; case 2: dayName = "Monday"; break; case 3: dayName = "Tuesday"; break; case 4: dayName = "Sunday"; break; case 5: dayName = "Sunday"; break; case 6: dayName = "Sunday"; break; case 7: dayName = "Sunday"; break; default: dayName = "Error"; break; }
If you accidentally forget to put in the break, execution will continue to the next statement in the switch statement even if there is another case: there.
Switch statement |