1. Introduction to Control Flow
1.1 What are Control Flow Statements
Control flow statements determine the order in which code is executed.
1.2 Importance
They help in:
- Decision making
- Repeating tasks
- Controlling execution path
1.3 Types
- Conditional statements
- Looping statements
- Jump statements
2. Conditional Statements
2.1 Overview
Conditional statements are used to execute code based on conditions.
2.2 if Statement
Syntax
if (condition) {
// code
}
Example
int age = 20;
if (age > 18) {
System.out.println("Adult");
}
2.3 if-else Statement
Syntax
if (condition) {
// true block
} else {
// false block
}
Example
int num = 5;
if (num % 2 == 0) {
System.out.println("Even");
} else {
System.out.println("Odd");
}
if-else-if Ladder
int marks = 75;if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 75) {
System.out.println("Grade B");
} else {
System.out.println("Grade C");
}
2.4 Nested if Statements
Definition
An if statement inside another if statement.
Example
int age = 20;
boolean hasID = true;if (age > 18) {
if (hasID) {
System.out.println("Allowed");
}
}
2.5 switch Statement
Syntax
switch (value) {
case 1:
// code
break;
case 2:
// code
break;
default:
// code
}
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");
}
Key Points
- Uses
breakto stop execution defaultexecutes if no case matches
3. Looping Statements
3.1 Introduction
Loops are used to repeat a block of code multiple times.
3.2 for Loop
Syntax
for (initialization; condition; update) {
// code
}
Example
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
3.3 while Loop
Syntax
while (condition) {
// code
}
Example
int i = 1;while (i <= 5) {
System.out.println(i);
i++;
}
3.4 do-while Loop
Syntax
do {
// code
} while (condition);
Example
int i = 1;do {
System.out.println(i);
i++;
} while (i <= 5);
Difference
- Executes at least once
3.5 Enhanced for Loop
Syntax
for (type variable : array) {
// code
}
Example
int[] numbers = {1, 2, 3, 4};for (int num : numbers) {
System.out.println(num);
}
4. Jump Statements
4.1 Introduction
Jump statements alter the normal flow of loops and methods.
4.2 break Statement
Definition
Terminates the loop immediately.
Example
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
System.out.println(i);
}
4.3 continue Statement
Definition
Skips the current iteration.
Example
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println(i);
}
4.4 return Statement
Definition
Exits from a method.
Example
public static int add(int a, int b) {
return a + b;
}
Conclusion
Control flow statements are essential for building logical and interactive Java programs. By mastering conditional statements, loops, and jump statements, you can control how your program behaves and responds to different situations. These concepts form the foundation for solving real-world programming problems.
Leave a Reply