❮ Previous Next ❯ \

Switch statement:

  1. The switch statement is a multi-directional control statements.
  2. Sometimes there is a need in program to make choice among number of alternatives, so for this we use switch statement.
  3. The general form is :

Example

switch(expression)
{
case constant1 :
//Statement sequence
break;
case constant2 :
//statement sequence
break;
..
..
case constant N:
//statement sequence
break;
default :
//default statement sequence
}

Here expression must be of type byte, short, int, char. Or an enumeration. Expression can also be of type string. Each value specified in the case statements must be a unique constant expression. Duplicate case values are not allowed.The type of each value must be compatible with the type of expression.

Mechanism:

The value of the expression is compared with each of the values in the case statements.
If match is found, the statement following that case statement is executed.
If none of the constant matches the value of the expression, then the default statement is executed.
If no case matches and no default is present, then no further action is taken.
The break statement is used inside the switch to terminate a statement sequence.
Let's see a simple example to demonstrate the Switch statement.

class SwitchDemo
{
public static void main(String[] args)
{
int month = 8;
String str;
switch (month)
{
case 1: str =" " ;
break;
case 2: str = " ";
break;
case 3: str = " ";
break;
case 4: str = " ";
break;
case 5: str = " ";
break;
case 6: str = " ";
break;
case 7: str = " ";
break;
case 8: str = " ";
break;
case 9: str = " ";
break;
case 10: str = " ";
break;
case 11: str = " ";
break;
case 12: str = " ";
break;
default: str = " ";
break;
}
System.out.println(str);
}
}
Output:
August

The break statement is optional. If we will omit the break, execution will continue into the next case. It is sometimes desirable to have multiple cases without break statements between them. Consider the following example :

class SwitchDemo1
{
public static void main(String args[])
{
for(int i=0;i<10;i++)
{
switch(i)
{
case 0:
case 1:
case 2:
System.out.println("Tapuuu");
break;
case 3:
case 4:
case 5:
System.out.println("Silan Software");
break;
default:
System.out.println("Silan");
}
}
}
}
Output:
Tapuuu
Tapuuu
Tapuuu
Silan Software
Silan Software
Silan Software
Silan
Silan
Silan
Silan
❮ Previous Next ❯



  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved