The switch case is also same as the if else if loop. It also checks multiple conditions for a single variable or statement.
Syntax:
switch(statement/variable)
{
case 1:
statements;
break;
case 2:
statements;
break;
....................
....................
case n:
statements;
break;
default:
statements;
}
import java.io.*;
class SwitchDemo
{
public static void main(String args[])throws IOException
{
char ch;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter an alphabet:");
ch = (char)br.read();
switch(ch)
{
case 'a':
System.out.println(ch+" is a vowel");
break;
case 'A':
System.out.println(ch+" is a vowel");
break;
case 'e':
System.out.println(ch+" is a vowel");
break;
case 'E':
System.out.println(ch+" is a vowel");
break;
case 'i':
System.out.println(ch+" is a vowel");
break;
case 'I':
System.out.println(ch+" is a vowel");
break;
case 'o':
System.out.println(ch+" is a vowel");
break;
case 'O':
System.out.println(ch+" is a vowel");
break;
case 'u':
System.out.println(ch+" is a vowel");
break;
case 'U':
System.out.println(ch+" is a vowel");
break;
default:
System.out.println(ch+" is not a vowel");
}
}
}
Output:
Syntax:
switch(statement/variable)
{
case 1:
statements;
break;
case 2:
statements;
break;
....................
....................
case n:
statements;
break;
default:
statements;
}
The statement or variable is compared to each of the cases for equality. The checking is done in a sequential manner. If any of the case satisfy the statement/variable then the statement associated with that case only executes. The break statement is important.
For more details consider the following example.If break statement is missing then the loop performs unwanted checking and generates unwanted output.
import java.io.*;
class SwitchDemo
{
public static void main(String args[])throws IOException
{
char ch;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter an alphabet:");
ch = (char)br.read();
switch(ch)
{
case 'a':
System.out.println(ch+" is a vowel");
break;
case 'A':
System.out.println(ch+" is a vowel");
break;
case 'e':
System.out.println(ch+" is a vowel");
break;
case 'E':
System.out.println(ch+" is a vowel");
break;
case 'i':
System.out.println(ch+" is a vowel");
break;
case 'I':
System.out.println(ch+" is a vowel");
break;
case 'o':
System.out.println(ch+" is a vowel");
break;
case 'O':
System.out.println(ch+" is a vowel");
break;
case 'u':
System.out.println(ch+" is a vowel");
break;
case 'U':
System.out.println(ch+" is a vowel");
break;
default:
System.out.println(ch+" is not a vowel");
}
}
}
Output: