freetimestudys@gmail.com          +91-7097633380
  Login Here                        

Switch

1) Switch statement is used to take multiple selections.
2) Curly brasses are mandatory if we are not taking we are getting compilation error.
3) Inside the switch It is possible to declare any number of cases but is possible to declare only one default.
4) Switch is taking the argument the allowed arguments are
                a. Byte
                b. Short
                c. Int 
                d. Char
                e. String(allowed in 1.7 version)
5) Float and double and long is not allowed for a switch argument because these are having more number of possibilities (float and double is having infinity number of possibilities) hence inside the switch statement it is not possible to provide float and double and long as a argument.
6) If the case is matched particular case will be executed if there is no case is matched default case is executed.

Syntax:

switch (key) {
case value:

break;

default:
break;
}

Java Images

Switch program

class Test
{
public static void main(String[] args)
  {
int a=10;
switch (a)
    {
case 10:System.out.println("10");
break;
case 20:System.out.println("20");
break;
case 30:System.out.println("30");
break;
case 40:System.out.println("40");
break;
default:System.out.println("default");
break;
     }
   }
}

intput and output

output:10

switch program using provide constant expressions

class Test
{
public static void main(String[] args)
{
int a=300;
switch (a)
 {
case 10+20+70:System.out.println("10");
break;
case 100+200:System.out.println("20");
break;
default :System.out.println("default");
break;
 }
  }
};

intput and output

output:20

switch program without break

class Test
{
public static void main(String[] args)
{
int a=10;
switch (a)
  {
case 10:System.out.println("10");
case 20:System.out.println("20");
case 30:System.out.println("30");
case 40:System.out.println("40");
break;
default: System.out.println("default");
break;
 }
  }
}

intput and output

output:10,,20,,30,,40

string argument using switch statement

class free
{
public static void main(String[] args)
 {
String str = "bbb"
switch (str)
  {
case "aaa" : System.out.println("Hai");
break;
case "bbb" : System.out.println("bye");
break;
case "ccc" : System.out.println("how");
break;
default : System.out.println("what");
break;
  }
  }
}

intput and output

Output:-bye

char argument using switch statement

class Test
{
public static void main(String[] args)
 {
char ch='a';
switch (ch)
 {
case 'a' : System.out.println("a");
break;
case 'b' : System.out.println("b");
break;
case 'c' : System.out.println("c");
break;
default : System.out.println("d");
break;
 }
  }
}

intput and output

output:a