What is a Switch Statement?
Syntax
switch(index){ case 0: //Do this and this break; case 1: //Do this and this break; case 2: //Do this and this: break; default: //For all other cases, do this break; }
where index is the variable whose value is matched. Since it’s an int, we match it with 0, 1, 2 and so on.
Example & Explanation
public class Main { public static void main(String[] args) { String day; switch (day){ case "Friday": //Woohoo, it's weekend time break; case "Saturday": //Rest time is now break; case "Sunday": //The day everyone waits for :) break; default: //Oh no, it's working day //This code is executed when value of variable 'day' //doesn't match with any of case above break; } } }
The same process goes on until a case is matched and break statement is reached. If none of the cases is matched, code after default: is executed. Please note that break statement is optional. However, you should consider using it because once a case is matched and break statement is reached, compiler skips rest of switch section. If you don’t use the break statement, it will still keep matching with other cases.