BASIC JAVA-2
Conditional Statement
If-Else
Switch case
Break
Continue
Loop
For Loop
While Loop
Do While Loop
Conditional Statements:
Conditional statements allow us to execute different blocks of code based on certain conditions. In Java, we commonly use the if-else and switch-case statements.
If-Else Statement:
The if-else statement executes a block of code if a specified condition is true, and another block of code if the condition is false.
int num = 10;
if(num > 0) {
System.out.println("Number is positive");
} else {
System.out.println("Number is non-positive");
}
Switch-Case Statement:
The switch-case
statement evaluates an expression and executes the corresponding block of code based on the value of the expression.
int day = 3;
switch(day) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
// Other cases
default:
System.out.println("Invalid day");
}
Loops:
Loops allow us to execute a block of code repeatedly until a specified condition is met. In Java, we have three types of loops: for
, while
, and do-while
.
For Loop:
The for
loop executes a block of code a specified number of times.
for(int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
While Loop:
The while
loop executes a block of code as long as a specified condition is true.
int i = 0;
while(i < 5) {
System.out.println("Iteration: " + i);
i++;
}
Do-While Loop:
The do-while
loop executes a block of code at least once, and then repeats the loop as long as a specified condition is true.
int i = 0;
do {
System.out.println("Iteration: " + i);
i++;
} while(i < 5);
Break and Continue:
In addition to loops and conditional statements, Java also provides break
and continue
statements for altering the flow of execution within loops.
Break Statement:
The break
statement is used to terminate the loop or switch-case statement it is within.
for(int i = 0; i < 10; i++) {
if(i == 5) {
break; // Exit the loop when i reaches 5
}
System.out.println("Iteration: " + i);
}
Continue Statement:
The continue
statement skips the current iteration of a loop and proceeds to the next iteration.
for(int i = 0; i < 5; i++) {
if(i == 2) {
continue; // Skip iteration when i equals 2
}
System.out.println("Iteration: " + i);
}
In summary, mastering conditional statements and loops in Java is crucial for writing efficient and organized code. These constructs, including if-else
, switch-case
, and various loop types, enable developers to control program flow and execute repetitive tasks effectively. The break
and continue
statements provide additional control within loops.
By understanding and applying these concepts, developers can create clearer and more maintainable code, enhancing their Java programming skills and ability to tackle diverse challenges. So, dive into these constructs, practice regularly, and elevate your Java development expertise.