Conditional Statements:
if-else Statement:
- Syntax:
- if (condition) { // Code to execute if condition is true } else { // Code to execute if condition is false }
switch Statement:
- Syntax:
- switch (expression) { case value1: // Code to execute if expression equals value1 break; case value2: // Code to execute if expression equals value2 break; default: // Code to execute if expression doesn't match any case }
Example:
int num = 10;
if (num > 0) {
System.out.println("Positive number");
} else {
System.out.println("Non-positive number");
}
Example:
char grade = 'B';
switch (grade) {
case 'A':
System.out.println("Excellent");
break;
case 'B':
System.out.println("Good");
break;
case 'C':
System.out.println("Average");
break;
default:
System.out.println("Not a valid grade");
}
Looping Constructs:
for Loop:
- Syntax:
- for (initialization; condition; update) { // Code to execute repeatedly }
while Loop:
- Syntax:
- while (condition) { // Code to execute repeatedly }
Example:
for (int i = 0; i < 5; i++) {
System.out.println("Iteration " + (i + 1));
}
Example:
int i = 0;
while (i < 5) {
System.out.println("Iteration " + (i + 1));
i++;
}
do-while Loop:
- Syntax:
- do { // Code to execute repeatedly } while (condition);
Example:
int i = 0;
do {
System.out.println("Iteration " + (i + 1));
i++;
} while (i < 5);
These constructs allow you to control the flow of your Java program based on conditions and perform repetitive tasks using looping mechanisms.
0 Comments