Switch Statement
There are several options and we have to choose only one option from the available ones, we
can use switch statement. Depending on the selected option a particular task can be performed
.A task represent one or more statements.
Example :
switch(variable )
{
case value1: statements1;
case value1: statements2;
case value1: statements3;
case valuen: statementsn;
[ default: defualt... statements;]
Here depending on the value of the variable, a particular task will be executed.
// Display the color depending on the color values
class Switch
{
public static void main(String[]arr)
{
char color ='O';
switch(color){
case 'W':
System.out.println("White color"); OUTPUT
case 'O':
System.out.println("Orange color");
case 'B':
System.out.println("Black color");
case 'G':
System.out.println("Green color");
default:
System.out.println("no match any color");
}
}
}
This Output is not expected . that it would display Orange.
but it is displaying the all color Starting from the Orange color.
In the following case O becomes true and hence . JVM display Orange and then excutes break. which terminats the switch block.
class Switch
{
public static void main(String[]arr)
{
char color ='O';
switch(color){
case 'W':
System.out.println("White color");
break;
case 'O':
System.out.println("Orange color");
break;
case 'B':
System.out.println("Black color");
break;
case 'G':
System.out.println("Green color");
break;
default:
System.out.println("no match any color");
}
}
}
OUTPUT
Orange color
class Switch
{
public static void main(String[]arr)
{
char color ='O';
switch(color){
case 'W':
System.out.println("White color"); OUTPUT
case 'O':
System.out.println("Orange color");
case 'B':
System.out.println("Black color");
case 'G':
System.out.println("Green color");
default:
System.out.println("no match any color");
}
}
}
This Output is not expected . that it would display Orange.
but it is displaying the all color Starting from the Orange color.
In the following case O becomes true and hence . JVM display Orange and then excutes break. which terminats the switch block.
class Switch
{
public static void main(String[]arr)
{
char color ='O';
switch(color){
case 'W':
System.out.println("White color");
break;
case 'O':
System.out.println("Orange color");
break;
case 'B':
System.out.println("Black color");
break;
case 'G':
System.out.println("Green color");
break;
default:
System.out.println("no match any color");
}
}
}
OUTPUT
Orange color
Break Statement
Break statement follows the three ways.
* break is used inside a loop to come out of it.
* break is used inside the switch block to come out of the switch block.
* break can be used in nested blocks to go to the end of a block. Nested block represent a lock
written within another block.
//
break;// represent the end of the block
0 comments:
Post a Comment