The switch statement can be considered as an alternative for if-elseif statements. It is a multi-branch of conditional statements. It works by checking the equality of different cases. It can be used with byte, short, char, and int primitive data types. Since Java 7 one can use Strings also in the switch statement.
Format :
switch(condition){ /* if condition matches case value code executes */ case value1 : // code for execution break; //optional case value2 : // code for execution break; //optional ..... ..... ..... default : //code to execute if all cases fail } |
Example :
Let's consider the following code.
int data=200; String dataString; switch(data){ /* if condition matches case value code executes */ case 100: dataString = "hundred"; break; //optional case 200: dataString = "two hundred"; break; //optional ..... ..... ..... default : dataString = "not from given cases"; } System.out.println("The number is: " + dataString); |
The output of the above input will be :
The number is: two hundred |
☛ Next >> Singleton Class In Java
A singleton class is a class which has one object at a time. In other wor ...
No comments:
Post a Comment