Home » Online Computer Education » Learn Fundamentals of Java Programming “The switch Statement in Java Programming ” Lesson 10

Learn Fundamentals of Java Programming “The switch Statement in Java Programming ” Lesson 10

The switch Statement

The switch statement is used to execute a block of code matching one value out of many possible values. The structure of the Java switch statement is as below:

switch (expression) {
case constant_1 : statements;
break;
case constant_2 : statements;
break;


default : statements;
break;
}

Within the switch statement, as you can see, there can be many case statements. The expression is compared with the constants in each case group and the matching case group is executed. If the expression evaluates to some constant = constant_1, the statements in the case group constant_1 are executed. Similarly, if the expression evaluates to constant_2, the statements in the case group constant_2 are executed. The break statement after each case group terminates the switch and causes execution to continue to the statements after the switch. If there is no match for the expression with any case group, the statements in the default part are executed.

The expression in the switch statement must evaluate to byte, short, int, or char.
The program code below demonstrates usage of the switch statement.

public class SwitchDemo {
publi c static void main(String[] args) {
int today = 5;
String day = “”;
switch (today) {
case 1: day = “Monday”;
break;
case 2: day = “Tuesday”;
break;
case 3: day = “Wednesday”;
break;
case 4: day = “Thursday”;
break;
case 5: day = “Friday”;
break;
case 6: day = “Saturday”;
break;
case 7: day = “Sunday”;
break;
default: day = “Incorre ct Day! “;
break;
}
System.out.println(day);
}
}

Figure 1.4d displays the output from the SwitchDemo program. Since the expression in the switch, is the variable today which is equal to 5, the case corresponding to the constant 5 is matched. The statements in this case 5 are executed which set the variable day to “Friday”. The break after the assignment causes the switch to terminate, execution of the statement after the switch, the System.out.println() statement takes place which prints the value of the variable day.

Java fundamentals  flow control 3

Can you guess what the output would be if the variable day was set to 10? Since 10 does not match any of the case statements, the default case would be executed and the output would be “Incorrect Day!”.

About

The main objective of this website is to provide quality study material to all students (from 1st to 12th class of any board) irrespective of their background as our motto is “Education for Everyone”. It is also a very good platform for teachers who want to share their valuable knowledge.

Leave a Reply

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