Java Switch-statement .

In this session i have discussed switch statement in Java .


Switch-Statement :

Switch is also a decision making and branching statemnet . It used to take the single selection from the multiple choice .

Switch-statement-syntax :

CSharp Switch image

Example : Write a java program that check the days of week according to given number .

 class Hello{ 
        
        public static void main(String args[]){  
   
            int i=4;
            switch(i){
            
                case 1:{
                
                    System.out.println("Sunday");
                    break;
                }
                case 2:{
                
                    System.out.println("Monday");
                    break;
                }
                case 3:{
                
                    System.out.println("Tuesday");
                    break;
                }
                case 4:{
                
                    System.out.println("Wednesday");
                    break;
                }
                case 5:{
                
                    System.out.println("Thursday");
                    break;
                }
                case 6:{
                
                    System.out.println("Friday");
                    break;
                }
                case 7:{
                
                    System.out.println("Saturday");
                    break;
                }
                default :{
                
                    System.out.println("Invalid number");
                    break;
                }
            
            }
       }
 } 
    OUTPUT : Wednesday
    


Example : Write a program that perform 1-Addition , 2-Subtraction , 3-multiplication , 4 Division .

   class Hello{ 
        
        public static void main(String args[]){  
            int op=3;
            int x=20;
            int y=10;
            switch(op){
            
                case 1:{
                
                    int sum=x+y;
                    System.out.println("Sum= "+sum);
                    break;
                }
                case 2:{
                
                    int sub=x-y;
                    System.out.println("Sub= "+sub);
                    break;
                }
                case 3:{
                
                    int multi=x*y;
                    System.out.println("Multi= "+multi);
                    break;
                }
                case 4:{
                
                    int div=x/y;
                    System.out.println("Div= "+div);
                    break;
                }
                default :{
                
                    System.out.println("Invalid Number");
                    break;
                }
            }
        }
   } 
    OUTPUT : Multi= 200
    


Welcome to AndroidATPoint.

back image                     next image