Java Control Statements
Types of Control Statements
• 1. Selection Statements:
• - if
• - if-else
• - switch
• 2. Iteration Statements:
• - for
• - while
• - do-while
if Statement - Example
• Example:
• int x = 10;
• if (x > 5) {
• System.out.println("x is greater than 5");
• }
if-else Statement - Example
• Example:
• int x = 3;
• if (x > 5) {
• System.out.println("x is greater than 5");
• } else {
• System.out.println("x is 5 or less");
• }
Nested if and if-else-if Ladder
• Nested if:
• if (x > 0) {
• if (x < 10) {
• System.out.println("x is between 1 and 9");
• }
• }
• if-else-if Ladder:
• if (x == 1) {
switch Statement - Example
• Example:
• int day = 2;
• switch(day) {
• case 1: System.out.println("Monday");
break;
• case 2: System.out.println("Tuesday"); break;
• default: System.out.println("Other day");
• }
for Loop - Example
• Example:
• for (int i = 0; i < 5; i++) {
• System.out.println("i = " + i);
• }
while Loop - Example
• Example:
• int i = 0;
• while (i < 5) {
• System.out.println("i = " + i);
• i++;
• }
do-while Loop - Example
• Example:
• int i = 0;
• do {
• System.out.println("i = " + i);
• i++;
• } while (i < 5);
break and continue - Example
• break:
• for (int i = 0; i < 5; i++) {
• if (i == 3) break;
• System.out.println(i);
• }
• continue:
• for (int i = 0; i < 5; i++) {
• if (i == 3) continue;
Summary
• ✔ if and if-else handle decision-making
• ✔ switch simplifies multi-branch conditions
• ✔ for, while, do-while enable looping
• ✔ break exits, continue skips
• ✔ Control flow is key to program logic