noscript

Java Switch statement is used to execute the statement based on the user’s choice. This means the user selects the choice and then the compiler according to the choice in the form of a case executes the statement.Java Switch statement provides us with cases to execute the statement. The switch provides us with a simplified way to execute the operation without writing so many if-else statements in the program. Switch statements are working like Java’ if-else-if ladder statement to check multiple conditions. Java Switch statement works with primitive data types and String also.

Important Points :

  1. The switch allows us to create multiple cases in the same switch statement.
  2. Case values should be literal and do not use variable values.
  3. Case values must be different with each case.
  4. Each case must end with a break statement to avoid multiple case execution.
  5. Switch statements can have a default statement at the end.

 Syntax :

 

switch(choice){

case value1:

//statement

break;

case value2:

//statement

break;

case value3:

//statement

break;

 

————–

 

case valueN:

//statement

break;

 

default:

//statement

}

Flow Diagram:

Example :

package com.switchdemo;

import java.util.Scanner;

public class SwitchDemo {

  public static void main(String[] args) {

Scanner scr = new Scanner(System.in);

System.out.println(“Please select the choice : 1.      Even or Odd, 2. Leap Year, 3. Negative or Positive   Number”);

    int choice = scr.nextInt();

//switch statement declaration

    switch(choice) {

      case 1:

System.out.println(“Enter the number to check   number is an even or not : “);

        int number = scr.nextInt();

        if(number%2==0) {

System.out.println(number + ” is an even number”);

}

        else {

System.out.println(number + ” is an odd number”);

}

      break;

      case 2:

System.out.println(“Enter year to check leap year or not : “);

        int year = scr.nextInt();

        if(year%4==0) {

System.out.println(year + ” is leap year”);

}

        else {

System.out.println(year + ” is not leap         year”);

}

        break;

        case 3:

System.out.println(“Enter number to check no is positive or negative :”);

          int num = scr.nextInt();

          if(num>0) {

System.out.println(num + ” is positive   number”);

}

          else if(num<0){

System.out.println(num + ” is negative   number”);

}

          else {

System.out.println(“Number is zero”);

}

        break;

        default:

System.out.println(“Invalid choice…..”);

}

}

}

For more information & classes Call: 7030000325
Registration Link: Click Here!

Author: Ambarish Durani

JAVA Trainer

IT Education Centre Placement & Training Institute

© Copyright 2023 | IT Education Centre.