Module 4 Control Structures Conditional Statements
2026-03-05 14:13 Tags: #java Author: Duke Hsu
Key concepts
-
Conditional Statements
Conditional statements allow a program to make decisions based on conditions. In Object-oriented programming , they are commonly used inside methods of a class to control object behavior
-
if Statement
Executes a block of code if a condition is true
-
if-else if-else statement
Used when checking multiple condition (more than 2 ), conditions are checked from top to bottom, once one condition is true, the rest are skipped.
-
Switch statement
Best used when comparing one variable to multiple fixed values - Variable can be: int, char, String, enum - break prevents fall-through - default is optional but recommended
-
Nested if statement
A nested if statement is an if statement placed inside another if statement. It is used when:
-
A second condition must be checked only if the first condition is true.
-
you need multiple levels of decision-making.
-
you are validating conditions step-by- step .
-
-
if -else statement
Executes one block if true, another if false
Real-Life Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | |
Switch Statements
Instead of writing many if...elsestatements, you can use the switch statement.
Think of it like ordering food in a restaurant : if you choose A, you get pizza, if you choose B , you get a burger. otherwise , you get nothing .
The switchstatement selects one of many code blocks to be executed.
Syntax
1 2 3 4 5 6 7 8 9 10 11 12 | |
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
References
Module 4 PPT