Thursday, August 27, 2020

Java Switch

Java Switch

The Java switch statement executes one statement from multiple conditions.  It allows a variable to be tested for equality against a list of values. Each value is called a case, and the  variable being switched on is checked for each case.

Syntax

switch(expression) {
case value1:
  //Statement(s)
  break;  //optional
case value2:
  //Statement(s)
  break;  //optional
//You can have any number of cases.
default:  //optional
   //Statement(s)
//code to be executed if all cases are not matched
}

The following rules apply to switch statement—

  •  The variable used in a switch statement can only be integers, convertable integers(byte, short, char), strings and enums.
  •  You can have any number of case statements within a switch. Each case is followed by the value to be compared to and a colon.
  •  The value for a case must be the same data type as the variable in the switch and it must be a constant or a literal.
  • When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached
  •  When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
  •  Not every case needs to contain a break appears, the flow of control will fall through to subsequent cases until a break is reached.
  •  A switch statement can have an optional default case, which must appear at the end of the switch. The default case can be used for performing a task when none of the cases is true. No break is needed in the default case.

 Flow diagram without using break keyword                                                                  

Example


//Java Program to demonstrate the use of Java Switch statement
public class Test {
 public static void main(String args[]) {
   //char grade = args[0].charAt(0)
   char grade = ‘A’;
   switch(grade) {
   case ‘A’:
   System.out.println(“Excellent”);
   break;
   case ‘B’:
   System.out.println(“Better”);
   break;
   case ‘C’:
   System.out.println(“Good”);
   break;
   case ‘D’:
   System.out.println(“You passed”);
   break;
   case ‘E’:
   System.out.println(“Try again”);
   break;
   case ‘F’:
   System.out.println(“Fail”);
   break;
   case default:
   System.out.println(“Invalid 
grade”);
   break;
    }
   System.out.println(“Your grade 
is” + grade);
  }
}

Output

Excellent
Your grade is A

The break keywords

When Java reaches a break  keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it’s a time for a break. There is no need for more testing.

A break can save a lot of execution time because it “ignores” the execution of all the rest of the code in the switch block.

 

The default keyword

The default keyword specifies some code to run if there is no case match:

Note that if the default statement is used as the last statement in a switch block, it does not need a break.

Flow diagram with using break keyword


         


Example

//this program to demonstrate the use of Java Switch Statement
public class Day {
 public static void main(String[] args) {
   int day = 3;
     switch(day) {
     case 1:
     System.out.println(“Monday”);
     break;
     case 2:
     System.out.println(“Tuesday”);
     break;
     case 3:
     System.out.println(“Wednesday”);
     break;
     case 4:
     System.out.println(“Thursday”);
     break;
     case 5:
     System.out.println(“friday”);
     break;
     case 6:
     System.out.println(“Saturday”);
     break;
     case 7:
     System.out.println(“Sunday”);
     break
     default:
     System.out.println(“Looking 
     break;
     }
  }
}
forward to the weekend”);

Output

Wednesday

Java Switch Statement with String

Java allows us to use strings in switch expression since SE 7. The case statement should be string literal.

Example

//this program to demonstrate the use of Java Switch Statement
public class SwitchStringExample{
public static void main(String[] args){
//Declaring String variable
 String levelString = “Expert”;
 int level = 0 ;
 //Using String in Switch expression
 switch(levelString) {
 //Using String Literal in Switch Case
   break;
   case “intermediate”: level=2;
   break;
   case “Expert”: level=3;
   break;
   default: level=0;              
    }
   System.out.println(“Your Level is:” + level);
  }
}

Output

Your Level is: 3

 

Java Nested Switch Statement

We can use switch statement inside other switch statement in Java. Is is known as Nested switch statement.

 Example:

//Java Program to demonstrate the use of Java Nested Switch
public class NestedSwitchExample {
  public static void main(String args[]) {
  //C - CSE, E - ECE, M – Mechanical
  char branch = 'C';
  int collegeYear = 4;
  switch( collegeYear ) {
  case 1:
  System.out.println("English,
 Maths,Science");
  break;
  case 2:
     switch( branch ) {
     case 'C':
     System.out.println("Operating System
 ,Java,Data Structure");
     break;
     case 'E':
           System.out.println("Micro processors
 ,Logic switching theory");
     break;
     case 'M':
     System.out.println("Drawing,
 Manufacturing Machines");
     break;
     }
   break;
  case 3:
    switch( branch ) {
    case 'C':
    System.out.println("Computer 
 Organization,MultiMedia");
    break;
    case 'E':
    System.out.println("Fundamentals of Logic Design, Microelectronics");
    break;
    case 'M':
    System.out.println("Internal 
 Combustion Engines, Mechanical Vibration");
    break;
    }
  break;
  case 4:
     switch( branch ) {
     case 'C':
     System.out.println("Data 
 Communication and Networks, MultiMedia");
     break;
     case 'E':
     System.out.println("Embedded 
 System,Image Processing");
     break;
     case 'M':
     System.out.println("Production 
 Technology,Thermal Engineering");
     break;
     }
  break;
    }
  }
}

Output:

Data communication and Networks, MultiMedia

Java Enum in Switch Statement

Java allows us to use enum in switch statement

Example:

//Java Program to demonstrate the use of Enum in switch statement  
public class JavaSwitchEnumExample      
  public enum Day {  Sun, Mon, Tue, Wed, Thu, Fri, Sat  }    
   public static void main(String args[])    
     {    
      Day[] DayNow = Day.values();    
      for (Day Now : DayNow) {    
      switch (Now) {    
      case Sun:    
      System.out.println("Sunday”);    
      break;    
      case Mon:    
      System.out.println("Monday”);    
      break;    
      case Tue:    
      System.out.println("Tuesday”);    
      break;         
      case Wed:    
      System.out.println("Wednesday”);    
      break;    
      case Thu:    
      System.out.println("Thursday”);    
      break;    
      case Fri:    
      System.out.println("Friday”);    
      break;    
      case Sat:    
      System.out.println("Saturday”);    
      break;    
       }    
     }    
  }    
}    

Output:

Sunday
Monday
Twesday
Wednesday
Thursday
Friday
Saturday

Java Wrapper in Switch Statement

Java allows us to use four wrapper classes: Byte, Short, Integer and Long in switch statement.

Example:

//Java Program to demonstrate the use of Wrapper class  
//in switch statement  
public class WrapperInSwitchCaseExample {       
  public static void main(String args[])  
   {         
    Integer age = 18;        
     switch (age) {  
     case (16):            
     System.out.println("You are under 
18.");  
     break;  
     case (18):                
     System.out.println("You are eligible 
for vote.");  
     break;  
     case (65):                
     System.out.println("You are senior 
citizen.");  
     break;  
     default:  
     System.out.println("Please give the 
valid age.");  
     break;  
    }             
  }  
}

 Output:

You are eligible for vote

No comments:

Post a Comment