Java switch example : Using switch statement in java


Switch branching is used to conditionally switch among multiple programs segments. The switch statement can be used as an alternative for if-else-if statement. It is used in situations where an expression being evaluated can have any one of multiple values. The use of switch statement improves the performance. We can have one switch case in another switch case known as nested switch statement.

Syntax:
switch (expression)
{
case constant1 : set of statements1;
break;
case constant2 : set of statements2;
break;
………
case constant(n) : set of statements(n);
break;
}

The expression is evaluated first. If the expression result matches any case constant, then set of statements belonging to that constant are executed.

A simple java switch example.

public class SwitchCaseExample {
public static void main(String args[])
{
System.out.println("Enter an alphabet : ");
char ch=(char)-1;
try
{
ch=(char)System.in.read();
}
catch(Exception e)
{
e.getStackTrace();
}
switch(ch)
{
case 'a' :System.out.println("You typed 'a'.");
break;
case 'b' :System.out.println("You typed 'b'.");
break;
case 'c' :System.out.println("You typed 'c'.");
break;
case 'd' :System.out.println("You typed 'd'.");
break;
default :System.out.println("Type alphabet between a-d");
break;
}
}
}

In the above example we have used a default case, the default case will execute if the switch cannot find any matching case constant.

Features of switch statement:

  1. The switch statement id different from the “if” statement. The “if” statement can test for any type of Boolean expression, whereas the switch statement only test for equality.
  2. No two case constants in the same switch can have same value, but in the nested switch the inner switch can have case constant similar to the outer switch.
  3. A switch statement is more efficient and easy to understand then a nested “if” statement.

No comments:

Post a Comment