• A.razaq

T12- Switch statement

we continue today the last part of selection structures with the ( Switch statement )

so what is switch statement ?

switch statement is a multiple-selection statement that performs different actions based on the possible values

lets observe the structure of switch case statement and try to understand it one by one


switch (expression) {

  case value1:
    // code
    break;
  
  case value2:
    // code
    break;
  
  default:
    // default statements
  }
  1. the expression is evaluated once

  2. the value of expression is compared with case ( if the value of expression matches the value of the case , the code in the matched case will be executed.

  3. when we have a match now the break takes action , break will stop the execution of more codes and case testing when the match is found and code is executed.

  4. default: default is like ( else ) it executes a code when there is no match at all

--------------------------------

we will understand it better by the next example.

first lets import the Scanner class into our program and follow the steps one by one


import java.util.Scanner;


Scanner input = new Scanner (System.in);
		System.out.println("Enter month in number");
		int month = input.nextInt();
		
		switch (month) {
		  case 1:
		    System.out.println("month is january");
		    break;
		  case 2:
		    System.out.println("month is february");
		    break;
		  case 3:
			    System.out.println("month is march");
			    break;
		  case 4:
			    System.out.println("month is april");
			    break;
		  default:
		    System.out.println("wtf!, the year is only 12 months ")




as you see above, we imported scanner and created an object of it and asked the user to enter a number , and we declared an integer number that stores the value taken from the user


now we will use this variable ( month) as a switch expression, meaning we will compare month value with every case we make

if month = case (1)

System.out.println("month is january") will execute

now break; will stop the program from executing more codes or look for another match.

if we dont have a match between month and all cases below

default: statement will execute the code like an ( else ) statement


lets test our program


lets try to enter the number 3



as you see the variable month value was 3 and 3 matched with case 3 so it printed the message above.


now lets try something that will not match , lets say we have 12 cases one for every month

and the user entered number 13



as you see no match , so the default will execute the code below it.

4 views0 comments

Recent Posts

See All