switch case in java

By | April 12, 2019

Switch case in java statement-: Like any other programming Java support switch case statement in java. we have seen that when one of the many alternative is to be selected we can use an if statement to control the selection .Some time complexity of such a program increasing dramatically when the number of alternative increases. the program become difficult to read and follow at times it may confused even the person who designed it.

For using switch case statement follow the process as like

We first declare that we are usingĀ  a switch statement, switch being a reserved keyword in Java. Then, we provide the name of the variable that we would like the switch statement to act on.

After creating a series of unwieldy if blocks, we create separate blocks in our switch statements using the case keyword. After each case keyword, we give a prescribed value and the following code will execute if the value of x matches with the value of the case keyword.

The switch statements also have a special case the default case which we pretty much always put at the end of a switch statement.

We can do that with the break keyword, which exists on a line of code all by itself and simply steps us up and out of the case that we are using in.

In addition to falling through from one case to anotherĀ  we can increase the complexity and the power of our switch statements by adding multiple cases to a single line. Because the cases freely fall through to each other.

A example of switch statement

public class SwitchExample {  

public static void main(String[] args) {  

    int number=30;  
    switch(number){  
    case 10: System.out.println("30");break;  
    case 20: System.out.println("30");break;  
    case 30: System.out.println("40");break;  
    default:System.out.println("Not in 10, 20 or 30");  
   
  }  
 }  
}

 

Output of this programme

40

Write a programme using switch statement

 

public class SwitchMonthExample {  
public static void main(String[] args) {  
    int month=5;  
    String monthString="";
    switch(month){  
    case 1: monthString="1 - January";
    break;  
    case 2: monthString="2 - February";
    break;  
    case 3: monthString="3 - March";
    break;  
    case 4: monthString="4 - April";
    break;  
    case 5: monthString="5 - May";
    break;  
    case 6: monthString="6 - June";
    break;  
    case 7: monthString="7 - July";
    break;  
    case 8: monthString="8 - August";
    break;  
    case 9: monthString="9 - September";
    break;  
    case 10: monthString="10 - October";
    break;  
    case 11: monthString="11 - November";
    break;  
    case 12: monthString="12 - December";
    break;  
    default:System.out.println(" Month is not available");  
    }  
    System.out.println(monthString);
}  
}

output of this programme

5-May

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *