The switch Statement

When we are using multiple selections with many alternatives then if/else statement can be cumbersome. Therefore switch/case statement can be used.
Scanner in = new Scanner(System.in); System.out.print("Select an option (1, 2, 3, 4, 5, 6, 7) "); int choice = in.nextInt(); switch (choice) { case 1: . . . break; case 2: . . . break; case 3: . . . break; case 4: . . . break; case 5: . . . break; case 6: . . . break; case 7: . . . break; default: // bad input . . . break; }
When execution will be started at the case label that matches the value on which the selection is performed. If a match is found, the code sequence following that case statement is executed and continues until the next break or the end of the switch. If none of the case labels match, then the default clause will be executed, if it is present.
Note that the case labels must be integers or enumerated constants. You cannot test strings (Before jdk1.7). But in jdk1.7 we can use case as string.
For example, the following is an error:

String input = . . .; switch (input) // ERROR

{   
case "A": // ERROR  
     . . .       break;   
. . .
}

class switchDemo { public static void main(String s[]) { String a='monday'; switch(a) { case 'monday': System.out.println("Print Monday"); } } }

comiple time error
C:\JavaProgram>javac switchDemo.java
switchDemo.java:11: incompatible types
found : java.lang.String
required: int
switch(a)
^
1 error

 



 

Latest Tutorial


Most Visited Tutorial