Professional Documents
Culture Documents
Control Structures (Part 1) : Java Control Structures Decision Control Structures If If-Else If-Else-If Switch
Control Structures (Part 1) : Java Control Structures Decision Control Structures If If-Else If-Else-If Switch
If
If-Else
If-Else-If
Switch
Is it important?
Yes No
Yes No
Do it now. Do it later.
General Format:
if ([expression]){
[statement or block of code];
}
or
if ([expression]) [statement];
General Format:
if ([expression]){
[statement1/codeblock1];
}
else {
[statement2/codeblock2];
}
or
if ([expression]) [statement1];
else [statement2];
• used for nested structures involving more than one condition that needs to be
satisfied
General Format:
if ([expression1]) {
[statement1/codeblock1];
}
else if ([expression 2]) {
[statement2/codeblock2];
}
else {
[statement3/codeblock3];
}
General Format:
switch ([switch expression])
{
case 1:
[statement1];
case 2:
[statement2];
case n:
[statement];
default:
..
}
*Property of STI J0047
There are a few differences of the switch statement when
compared with the if statements:
1. multiple statements/blocks of code can be executed without using
braces
2. when a case in the switch statement has been matched, statements
for the matched case and succeeding cases are executed
3. break statements must be used to prevent execution of subsequent
cases
4. cannot be used for ranged values