Switch Statement
Optional NodePremium Content - Free Preview
If you want to run a block of code if a condition is true, you can use an if statement. If you want to run different code for multiple conditions, you can use multiple else if
statements. In the last node, the Java Help Menu printed a different statement for different values of the selection
variable:
if(selection == 1){
System.out.println("for(initialization; condition; iteration){ statment; }");
}
else if(selection == 2){
System.out.println("while(condition){ statement; }");
}
else if(selection == 3){
System.out.println("do{ statement; } while(condition);");
}
switch statement
Each if statement just checked if selection
equaled different values. To avoid repeating variable equality expressions, Java has another control structure for cases like these: the switch
statement. Its general common form looks like this:
switch (variable) {
case value1:
statements1
break;
case value2:
statements2
break;
// (more cases) ...
default: // optional default case
statementDefault
}
// switch statement over and code continues...
The previous menu code could be improved with the switch
statement:
switch (selection){
case 1:
System.out.println("for(initialization; condition; iteration){ statement; }");
break;
case 2:
System.out.println("while(condition){ statement; }");
break;
case 3:
System.out.println("do{ statement; } while(condition);");
break;
}
This code is similar to the else-if statements, but slightly clearer and more optimized. Java will look at the value of the selection variable and then jump to the case that matches its value.
End of Free Content Preview. Please Sign in or Sign up to buy premium content.
Comments
Raz Levi
Nov 27, 2:07 AMmy code
hey. im need help.. im didnt understand
Learneroo
Nov 27, 10:12 AMLook at the general syntax of the
switch
statement. Here's one with only one case, which will print "word" whennum
is 1:You need to use the switch statement to print a day of the week for each number from 1 to 7, and
default
to "Not a day" for other numbers.thales
Jul 9, 1:12 PMHere is my code: