A. Conditional Statements:
- if statement: The if statement is a conditional statement used to execute a block of code if a condition is true.
Example:
int num = 10;
if (num > 0) {
System.out.println("Number is positive");
}
- switch statement: The switch statement allows a program to evaluate an expression and execute code based on the value of the expression.
Example:
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
break;
}
B. Looping Statements:
- for loop: The for loop is a control flow statement that allows a block of code to be executed repeatedly.
Example:
for (int i = 1; i <= 5; i++) {
System.out.println("Count is: " + i);
}
- while loop: The while loop is a control flow statement that allows a block of code to be executed repeatedly as long as a specified condition is true.
Example:
int i = 1;
while (i <= 5) {
System.out.println("Count is: " + i);
i++;
}
- do-while loop: The do-while loop is similar to the while loop, but the block of code is executed at least once, even if the condition is false.
Example:
int i = 1;
do {
System.out.println("Count is: " + i);
i++;
} while (i <= 5);
C. Jump Statements:
- break statement: The break statement is used to terminate the current loop or switch statement.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
System.out.println("Count is: " + i);
}
- continue statement: The continue statement is used to skip the current iteration of a loop and continue with the next iteration.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue;
}
System.out.println("Count is: " + i);
}
- return statement: The return statement is used to exit a method and return a value to the caller.
Example:
public int add(int num1, int num2) {
int sum = num1 + num2;
return sum;
}