JAVA-Flow Control Statements - Notes By ShariqSP
Flow Control Statements in Java
In Java, flow control statements are used to control the order of execution of statements in a program. They allow you to make decisions, repeat statements, and branch based on conditions.
Simple If Statement
The simple if statement is used to execute a block of code only if the condition specified is true.
if (condition) {
// code to be executed if condition is true
}
If-else Statement
The if-else statement is used to execute one block of code if the condition is true and another block of code if the condition is false.
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
If-else-if Statement
The if-else-if statement is used to test multiple conditions. It executes different blocks of code depending on the true condition.
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if all conditions are false
}
quiz
Long answers
Switch Statement
The switch statement allows you to select one of many code blocks to be executed based on the value of an expression.
switch (expression) {
case value1:
// code to be executed if expression equals value1
break;
case value2:
// code to be executed if expression equals value2
break;
default:
// code to be executed if expression doesn't match any case
}
quiz
Long answers
Looping Statements in Java
Looping statements in Java are used to execute a block of code repeatedly based on a condition.
For Loop
The for loop executes a block of code a specified number of times.
for (initialization; condition; update) {
// code to be executed
}
Example:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
While Loop
The while loop executes a block of code as long as the specified condition is true.
while (condition) {
// code to be executed
}
Example:
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Do-While Loop
The do-while loop is similar to the while loop, but the condition is evaluated after the execution of the block.
do {
// code to be executed
} while (condition);
Example:
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
For-Each Loop
The for-each loop is used to iterate over elements in an array or a collection.
for (type variable : array/collection) {
// code to be executed
}
Example:
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
quiz
Long answers