Switch
switch is a multiple branching statement.It will check the case which case is true that case statement will executed.Otherwise default statement will be executed.
syntax
switch(variable) { case x: #statement; case y: #statement; default: #statement; }
Example-1
public class Main { public static void main(String[] args) { int age = 20; switch(age) { case 18: System.out.println("your age Eighteen"); break; case 19: System.out.println("your age Nineteen"); break; case 20: System.out.println("your age Twenty"); break; default: System.out.println("Not allow"); } } }
Output
your age Twenty
Example-2
public class Main { public static void main(String[] args) { char a = 'b'; switch(a) { case 'a': System.out.print("apple"); break; case 'b': System.out.print("ball"); break; case 'c': System.out.print("cat"); break; case 'd': System.out.print("dog"); break; default: System.out.print("Error"); break; } } }
Output
ball