SWITCH CASE
Switch case is the advance form of java. Imagine that you are trying to ascertain the current mobile balance in your phone. After typing the USSD code a message will appear with number of options asking what you want to perform and when you type 2 for balance, it finally shows the balance and then asks for other option. This is what the switch case is. It is equal to that. It is aimed to take optional input from user and to show result according to that.
Its syntax is :-
switch(int/ char value/ expression)
{
Case 1/ any character value : statement 1 and 2 then break;
Case n: means the case can be till n no of options. Break;
Default : statement 1 or 2….
}
IMPORTANT POINTS
1. Every case should be ended with break statement.
2. If break statement will not be there then fall through condition will occur and the program will move to next case without user’s permission.
3. There should be given only the int or char type value in switch().
4. Default case is used for the default statement means if user has given wrong input then it will directly move into default statement whatever will be written there it will print. Like when you input wrong option then it shows “wrong option entered !”.
NESTED SWITCH
Nested switch case is the case when we use a switch under the switch. This is there in if case also. From my point of view at this level nested switch will hardly be asked.
The program which showed in the video is as follows
import java.io.*;
import java.util.*;
class optional
{
public void main()throws IOException
{
Scanner sc=new Scanner(System.in);
int opt;
System.out.println("MAIN MENU");
System.out.println("1---> 1st output");
System.out.println("2---> 2nd Output ");
opt=sc.nextInt();
switch(opt)
{
case 1 : System.out.println("Hii this is the first statement "); break;
case 2 : System.out.println("Hello this is the second statement ");
default : System.out.println("Wrong input entered ");// now see output here used default case for the program to show when wrong input entered //
}
}
}
CONCLUSION
So friends this is what the switch case was. We will upload further videos on this after taking some important and awesome programs to make you this concept a crystal clear.