Square CSS

Showing posts with label switchstatement. Show all posts
Showing posts with label switchstatement. Show all posts

Saturday, October 20, 2018

Switch Statement In Java

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            




                    A singleton class is a class which has one object at a time. In other wor ... 


Some Algorithms

Algorithm: Tower of Hanoi

Tower of Hanoi consists of three towers called as pegs with n number of rings. Rings are of different size.  Conditions to be fulfill...

Popular Posts