Site icon JavaGoal

Switch statement Java

The switch statement in Java is like the if-else-if ladder statement. To reduce the code complexity of the if-else-if ladder switch statement comes. The Switch statement is the alternate the of if else if ladder statement.

Let’s discuss the switch case java and switch case in java example programs

Youtube video available in the Hindi language

Youtube video available in the Hindi language – Java Programming Goal

Here is the table content of this article we will cover all the parts of this topic.
1. switch statement in Java?
2. Rules of the switch statement Java
3. Nested switch statements in Java?
4. Does Java switch multiple cases?
5. switch case without a break statement?
6. switch case with char?
7. switch case with wrapper classes?

8. Why does float values are not allowed in the switch statement?

switch statement programs for practices

The switch statement executes one block of the statement from multiple blocks of statements based on condition. In the switch statements, we have a number of choices and we can perform a different task for each choice.

switch(variable/expression)
 {
   case value1 :
      // code inside the case value1
      break; // optional
   
   case value2 :
      // code inside the case value2 
      break; // optional
    .
    .
    .
    default : 
           // code inside the default case .
}

Rules of the Switch statement Java

  1. An expression can be of byte, short, int, long, enum types, String, and some wrapper types like Byte, Short, Int, and Long. You can place a variable or an expression in between the brackets of the switch().
  2. You can create any number of cases in the switch statement.
  3. The case value must be literal or constant. The case value type should be a type of expression.
  4. Each case should be unique. If you create a duplicate case value, it will throw a compile-time error.
  5. Each case has a break statement which is optional. Switch statement uses it to terminate a statement sequence and jumps the control after the switch expression.
  6. If we don’t use the break statement in any case then JVM doesn’t break the execution follow until it finds the break statement or the end of the switch statement.
  7. The default case is optional for the switch case and it must be placed at the end of the switch statement. If all of the above cases are false then JVM executes the default case and the default case doesn’t need a break statement.

switch case program in java

public class ExampleOfSwitch
{  
  public static void main(String[] args)
  {  
     //Declaring a variable for switch expression  
     int noOfDays = 28;  
     switch(noOfDays) //Switch expression  
    {  
   	 //Case statements  
   	case 28: 
        System.out.println("Only February month has 28 days");  
    	break;  
    	case 30:
        System.out.println("April, June, August, October, December has 30 days");  
    	break;  
   	case 31: System.out.println("January, March, May, July, September, November has  
        31 days");  
    	break;  
    	//Default case statement  
   	default: System.out.println("Please enter valid no of days");  
    }  
   }  
}  

Output: Only February month has 28 days

In this example, we want to print the name of months based on their days. Here we declared a variable and used it in the switch expression. The switch expression variable is a type of int. Here, we created three cases of int type and each case has different codes according to our requirements. Here we are using the default case also.

Nested Switch statements in Java

Let’s discuss the nested switch in java programs. There are some rules or important points that help you to understand them better.
We can use a switch statement inside another switch statement. This is known as the Nested switch-case statements in Java. The inner switch statement can be part of any case of an outer switch. If the condition of the outer switch statement is true the JVM checks the condition of the inner switch statement.

switch(variable/expression)
 {
   case value1 :
      // code inside the case value1
      break; // optional
   
   case value2 :
      // code inside the case value2 
      break; // optional
   case value3 : 
   switch(variable/expression)
   {
      case valueOne :
         // code inside the case valueOne 
         break; // optional
   
      case valueTwo :
         // code inside the case valueTwo 
         break; // optional
      .
      .
      .
      default : 
         // code inside the default case .
   }
   .
   .
   .
    default : 
           // code inside the default case .
}

In the above syntax:
Step1: JVM will check the condition of the outer switch statement. If it returns true then control flow enters the outer Switch statement.
Step2: JVM will execute the block statement with the matched case.
Step3: JVM will check the condition of the inner switch statement. If it returns true then the control flow enters the inner Switch statement.

An essential point of Nested Switch statements in Java

1. The inner switch statement must be part of any case of the outer switch statement. You can’t write inner switch statements outside the cases.
2. You can use the inner switch statement in the default case of the outer switch statement.

java switch case example

public class ExampleOfNestedSwitch
{
   public static void main(String[] args)
   {
      //Declaring a variable for switch expression
      int year = 3;
      int marks = 80;

      switch(year) //Switch expression
      {
         //Case statements
         case 1:
         System.out.println("First year students are not eligible for scholarship ");
         break;
         case 2:
         System.out.println("Second year students are not eligible for scholarship");
         break;
         case 3:
         switch(marks)
         {
            case 50:
            System.out.println("You are not eligible for scholarship");
            break;
            case 80:
            System.out.println("Congrats!!!!! you are eligible for scholarship");
            break;
         }
         break;
         //Default case statement
         default: System.out.println("Please enter valid year");
     }
   }
}

Output: Congrats!!!!! you are eligible for scholarship

1. In the given program we initialized two variables: year and marks
2. The outer switch statement is checking the condition and sees which year of a student falls in the category of
student.
3. The inner switch statement is checking the condition and sees the marks of the student. If marks don’t match with the case, then the default case of the inner switch statement is executed.
4. Otherwise, the switch case will trigger the default case

Java Switch multiple cases

In java switch case is used to reduce the complexity of the if-else ladder. We can use multiple cases in switch statement. In this topic, we will see how we can use switch case java with combined cases.

As you already know the Switch statement, can contain multiple cases. You can write multiple cases in combined form in the Switch statement. It totally depends upon the user because sometimes the user wants to perform the same action on different inputs. So in that case user can combine the case. It means you can combine multiple cases of the Switch statement.

Syntax

switch(variable/expression)
 {
   case value1 :
   case value2 :
   case value3 :
   case value4 :
      // code inside the combined case
      break; // optional
   
   case value5 :
   case value6 :
   case value7 :
   case value8 :
      // code inside the combined case value 
      break; // optional
    .
    .
    .
    default : 
           // code inside the default case .
}

You can combine multiple cases as you can see in syntax.
Whenever you want to combine multiple cases you just need to write a case with case labels and colons(:). You can’t provide the break statement in between combined cases.

public class ExampleOfSwitch
  {  
     public static void main(String[] args)
     {  
          //Declaring a variable for switch expression  
          int noOfMonth = 5;  
          switch(noOfMonth) //Switch expression  
          {  
            //Case statements  
            case 1: 
            case 3:
            case 5:
            case 7:
            case 9:
            case 11:
                            System.out.println("It has 31 days");  
                    break;  
            case 2:
                            System.out.println("It has 28 days");  
                    break;  
            case 4:
            case 6:
            case 8:
            case 10:
            case 12: 
                    System.out.println("It has 30 days");  
                    break;  
            //Default case statement  
            default: System.out.println("Please enter valid input");  
           }  
       }  
 }  

Output: It has 31 days

Explanation of Java Switch multiple cases

In the above example, We want to print the numbers of the day in the month. In a year, some months have equal numbers of days but some have different numbers of days. So, we decide to combine all the cases in which we want to perform the same task. The example of months, As we know only February has 28 days the rest of the months contain either 30 or 31 days. So, we combined some cases because those months have the same days.

Switch case without break statement

Each case may or may not be followed by a break statement. Because the break statement is optional for each block. The break statement is optional in the switch statement. We will read how behaves Switch case works without a break statement.

Why do we use the break statement in the switch case?

The break statement is used inside the switch to terminate a statement sequence and jumps the control after the switch expression. Whenever a break statement is found in the Switch statement the control flow directly jumps out of the Switch statement.

NOTE: If a break statement is not used in any case the execution will continue into the next case until a break statement is reached. If no break statement is found in any case then it executes all the cases including the default case. It is also known as fall-through.

Syntax

switch(variable/expression)
 {
   case value1 :
      // code inside the case value1
      // Break is not used because it is optional
   
   case value2 :
      // code inside the case value2 
      // Break is not used because it is optional
    .
    .
    .
    default : 
           // code inside the default case.
}

In Syntax, you can see the break statement is optional.

public class ExampleOfSwitch
{  
   public static void main(String[] args)
   {  
      //Declaring a variable for switch expression  
      int noOfDays = 28;  
      switch(noOfDays) //Switch expression  
      {  
   	 //Case statements  
   	 case 28: 
         System.out.println("Only February month has 28 days");  
         // NOTE: There is no break statement after the case 28
    	 case 30:
         System.out.println("April, June, August, October, December has 30 days");  
    	 break;  
   	
         case 31: System.out.println("January, March, May, July, September, November has  
                  31 days");  
    	 break;  
    	//Default case statement  
   	 default: System.out.println("Please enter valid no of days");  
      }  
   }  
}  

Output: Only February month has 28 days
April, June, August, October, December has 30 days

You can see in the example: Compiler doesn’t find the break statement after case 28 and it executes the next case also.

switch case with char?

The switch statement executes a single block of the statement from the multiple blocks of statements based on condition. In the switch statements, we have a number of choices and we can perform a different task for each choice.

public class ExampleOfSwitch
 {  
	public static void main(String[] args)
	{  
	     //Declaring a variable for switch expression  
	     char alphabet = 'b';  
	     switch(alphabet) //Switch expression  
	     {  
		   	 //Case statements  
		   	case 'a': 
		   	System.out.println("This is character 'a' ");
		   	break;
		   	case 'b':
		   	System.out.println("This is character 'b' ");
		   	break;
		   	case 'c':
		   	System.out.println("This is character 'c' ");
		   	break;  
		        //Default case statement  
		   	default: System.out.println("Please enter valid input");  
	      }  
	  }  
}  

Output: This is character ‘b’

In this example, we want to print the name of the character based on the input entered by the user. 1. Firstly, we declared a variable of char type.
2. After that, we are using that variable in the switch expression. The switch expression variable is a type of char now.
3. So, we created three cases of type char. Each case has different codes according to our requirements.
4. We have a default case at the end of the switch if the user enters any wrong input which doesn’t match with any case then the default case will execute.

The Switch expression always allows a valid input. So we can try it in some different manner. Here we are declaring a String and providing only one character from the to Switch statement.

public class ExampleOfSwitch
 {  
	public static void main(String[] args)
	{  
	     //Declaring a String  
	     String alphabet = "HiHello";  
	     switch(alphabet.charAt(0)) //Switch expression  
	     {  
		   	 //Case statements  
		   	case 'H': 
		   	System.out.println("This is character 'H' ");
		   	break;
		   	case 'b':
		   	System.out.println("This is character 'b' ");
		   	break;
		   	case 'c':
		   	System.out.println("This is character 'c' ");
		   	break;  
		        //Default case statement  
		   	default: System.out.println("Please enter valid input");  
	      }  
	  }  
}  

Switch case with wrapper classes

In JAVA we can use the wrapper class for the switch statement. But java allows only four types of Wrappers that are Byte, Short, Integer, and Long.

Here is an example of a Wrapper class Integer:

You can see in the above syntax how to use the Switch case with wrapper classes. You can’t use the object of the Wrapper class in the case. Because the case always accepts a constant value.

public class ExampleOfSwitch
{  
   public static void main(String[] args)
   {  
     //Declaring a wrapper variable for switch expression  
     Integer year = 3;  
     int marks = 80;
     
     switch(year) //Switch expression  
     {  
   	 //Case statements  
   	case 1: 
   	System.out.println("First year students are not eligible for scholarship ");
   	break;
   	case 2:
   	System.out.println("Second year students are not eligible for scholarship");
   	break;
   	case 3:
	System.out.println("Congrats!!!!! you are eligible for the scholarship");
	break;
        //Default case statement  
	default: System.out.println("Please enter valid year");  
     }  
   }  
}  

Output: Congrats!!!!! you are eligible for the scholarship

Why does float values are not allowed in the switch statement?

As you know the Switch statement makes a comparison of expression with the cases. If any match is found, the matched case gets executed. But the comparison of float values doesn’t guarantee always the correct results. This is why float comparison is not recommended even with if-else conditions.
Let’s say we have two floating numbers x and y. Comparing two floating-point numbers can be inaccurate when the decimal equivalents of x and y look the same to a reasonable precision.

Here we will discuss the different types of switch statement programs for practices. You can simply try these programs on your end also. switch statement programs for practices:

switch statement programs for practices

1. Write a Java program that takes input from the user and uses a switch statement to perform different actions based on the user’s input.

import java.util.Scanner;

public class UserInputSwitch {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Please enter a number between 1 and 4:");
        int number = input.nextInt();

        switch (number) {
            case 1:
                System.out.println("You entered 1.");
                break;
            case 2:
                System.out.println("You entered 2.");
                break;
            case 3:
                System.out.println("You entered 3.");
                break;
            case 4:
                System.out.println("You entered 4.");
                break;
            default:
                System.out.println("Invalid input. Please enter a number between 1 and 4.");
                break;
        }
    }
}

2. Write a java program that uses a switch statement to print the name of the month corresponding to a given integer value.

import java.util.Scanner;

public class MonthName {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Please enter a month number (1-12):");
        int month = input.nextInt();

        String monthName;

        switch (month) {
            case 1:
                monthName = "January";
                break;
            case 2:
                monthName = "February";
                break;
            case 3:
                monthName = "March";
                break;
            case 4:
                monthName = "April";
                break;
            case 5:
                monthName = "May";
                break;
            case 6:
                monthName = "June";
                break;
            case 7:
                monthName = "July";
                break;
            case 8:
                monthName = "August";
                break;
            case 9:
                monthName = "September";
                break;
            case 10:
                monthName = "October";
                break;
            case 11:
                monthName = "November";
                break;
            case 12:
                monthName = "December";
                break;
            default:
                monthName = "Invalid month";
                break;
        }

        System.out.println("You entered " + monthName);
    }
}

3. Write a java program that takes a grade letter from the user (A, B, C, D, or F) and prints the corresponding GPA value

import java.util.Scanner;

public class GradePointAverage {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Please enter a grade letter (A, B, C, D, or F):");
        String grade = input.next().toUpperCase();

        double gpa;

        switch (grade) {
            case "A":
                gpa = 4.0;
                break;
            case "B":
                gpa = 3.0;
                break;
            case "C":
                gpa = 2.0;
                break;
            case "D":
                gpa = 1.0;
                break;
            case "F":
                gpa = 0.0;
                break;
            default:
                gpa = -1.0;
                break;
        }

        if (gpa == -1.0) {
            System.out.println("Invalid grade letter");
        } else {
            System.out.println("Your GPA is " + gpa);
        }
    }
}

4. Write a java program that takes a day of the week from the user (1-7) and prints a corresponding message

import java.util.Scanner;

public class DayOfWeek {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Please enter a day of the week (1-7):");
        int day = input.nextInt();

        String message;

        switch (day) {
            case 1:
                message = "It's Monday!";
                break;
            case 2:
                message = "It's Tuesday!";
                break;
            case 3:
                message = "It's Wednesday!";
                break;
            case 4:
                message = "It's Thursday!";
                break;
            case 5:
                message = "It's Friday!";
                break;
            case 6:
                message = "It's Saturday!";
                break;
            case 7:
                message = "It's Sunday!";
                break;
            default:
                message = "Invalid day of the week";
                break;
        }

        System.out.println(message);
    }
}

5. Write a java program that converts a numeric grade into a letter grade based on a standard grading scale

import java.util.Scanner;

public class GradeConverter {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Please enter a numeric grade (0-100):");
        int grade = input.nextInt();

        String letterGrade;

        switch (grade / 10) {
            case 10:
            case 9:
                letterGrade = "A";
                break;
            case 8:
                letterGrade = "B";
                break;
            case 7:
                letterGrade = "C";
                break;
            case 6:
                letterGrade = "D";
                break;
            default:
                letterGrade = "F";
                break;
        }

        System.out.println("Your letter grade is " + letterGrade);
    }
}

6. Write a java program that calculates the total cost of an order based on the number of items and a per-item cost that varies depending on the type of item

import java.util.Scanner;

public class OrderCalculator {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Please enter the quantity of items in your order:");
        int quantity = input.nextInt();

        System.out.println("Please enter the type of item in your order (1-3):");
        int itemType = input.nextInt();

        double itemCost;

        switch (itemType) {
            case 1:
                itemCost = 5.0;
                break;
            case 2:
                itemCost = 10.0;
                break;
            case 3:
                itemCost = 15.0;
                break;
            default:
                System.out.println("Invalid item type. Using default cost of $10.0");
                itemCost = 10.0;
                break;
        }

        double totalCost = quantity * itemCost;

        System.out.println("Your total cost is $" + totalCost);
    }
}

7. Write a java program that determines the number of days in a given month and year

import java.util.Scanner;

public class DaysInMonth {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.println("Please enter a month (1-12):");
        int month = input.nextInt();

        System.out.println("Please enter a year:");
        int year = input.nextInt();

        int numDays;

        switch (month) {
            case 2:
                if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) {
                    numDays = 29;
                } else {
                    numDays = 28;
                }
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                numDays = 30;
                break;
            default:
                numDays = 31;
                break;
        }

        System.out.println("There are " + numDays + " days in that month.");
    }
}
Exit mobile version