Java Conditional Statements and Loops by Josh
Java Conditional Statements and Loops by Josh
Conditional statements in Java allow the program to execute certain blocks of code based on
specific conditions. These conditions are typically boolean expressions (i.e., expressions that
evaluate to true or false). Java provides several types of conditional statements:
if Statement
if-else Statement
if-else-if Ladder
switch Statement
Let's go through each one in detail with examples.
1. if Statement
The if statement is the simplest form of a conditional statement. It checks a condition, and if the
condition is true, it executes a block of code. If the condition is false, the block of code is
skipped.
Syntax:
if (condition) {
// code to be executed if the condition is true
}
Example:
public class IfExample {
public static void main(String[] args) {
int age = 18;
Output:
You are eligible to vote.
Explanation: In this example, the condition checks if age is greater than or equal to 18. Since
age = 18, the condition is true, so the message "You are eligible to vote." is printed.
2. if-else Statement
The if-else statement allows you to execute one block of code if the condition is true, and a
different block of code if the condition is false.
Syntax:
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
Example:
public class IfElseExample {
public static void main(String[] args) {
int age = 16;
Output:
You are not eligible to vote.
Explanation: In this case, the condition checks if age is greater than or equal to 18. Since age =
16, the condition is false, and the code inside the else block is executed, printing "You are not
eligible to vote."
3. if-else-if Ladder
The if-else-if ladder is used when you have multiple conditions to check. It allows you to check
several conditions sequentially. The first condition that evaluates to true will execute its
corresponding block of code.
Syntax:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else if (condition3) {
// code to be executed if condition3 is true
} else {
// code to be executed if none of the conditions are true
}
Example:
public class IfElseIfExample {
public static void main(String[] args) {
int score = 85;
Output:
Grade B
Explanation: Here, the score is 85, which satisfies the condition score >= 80, so "Grade B" is
printed. If the score was 92, "Grade A" would have been printed.
4. switch Statement
The switch statement is a more efficient way of handling multiple possible conditions based on a
single variable or expression. It compares the value of the variable with a list of values (called
"cases") and executes the corresponding block of code for the first match.
Syntax:
switch (expression) {
case value1:
// code to be executed if expression equals value1
break;
case value2:
// code to be executed if expression equals value2
break;
case value3:
// code to be executed if expression equals value3
break;
default:
// code to be executed if none of the cases match
}
Example:
public class SwitchExample {
public static void main(String[] args) {
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;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}
}
}
Output:
Wednesday
Explanation: In this example, the variable day is 3. The switch statement matches day with case
3, so "Wednesday" is printed. The break statement ensures that the program exits the switch
block after the matched case.
If no cases match, the default block is executed.
Conclusion
Conditional statements in Java help control the flow of execution based on conditions. They are
fundamental to implementing logic in programs, such as decision-making, branching, and
responding to user input. By using these constructs, you can create more flexible and dynamic
Java applications.
Output:
1
2
3
4
5
Explanation:
Initialization: int i = 1 starts the loop with i set to 1.
Condition: i <= 5 ensures the loop runs as long as i is less than or equal to 5.
Iteration: i++ increments the value of i by 1 after each loop iteration.
Output:
5
4
3
2
1
Explanation:
Initialization: int i = 5 starts the loop with i set to 5.
Condition: i >= 1 ensures the loop runs as long as i is greater than or equal to 1.
Iteration: i-- decrements the value of i by 1 after each loop iteration.
Output:
i: 1, j: 10
i: 2, j: 9
i: 3, j: 8
i: 4, j: 7
i: 5, j: 6
Explanation:
Initialization: int i = 1, j = 10 starts i at 1 and j at 10.
Condition: i <= 5 ensures the loop runs while i is less than or equal to 5.
Iteration: i++ increments i by 1, and j-- decrements j by 1 in each iteration.
Output:
***
***
***
Explanation:
The outer for loop runs 3 times (from i = 1 to i = 3).
The inner for loop also runs 3 times (from j = 1 to j = 3), printing a * on each iteration.
After each iteration of the inner loop, the outer loop moves to the next line with
System.out.println().
Output:
1
2
3
4
5
Explanation:
The for loop starts with i = 0 and runs as long as i < numbers.length. The numbers.length is the
length of the array, so the loop runs for each element.
Inside the loop, numbers[i] prints each element of the array.
Example:
public class EnhancedForLoop {
public static void main(String[] args) {
// Declare an array of integers
int[] numbers = {1, 2, 3, 4, 5};
// Use the enhanced for loop to print each element in the array
for (int num : numbers) {
System.out.println(num);
}
}
}
Output:
1
2
3
4
5
Explanation:
The enhanced for loop automatically iterates over each element in the numbers array.
Each element is assigned to the variable num and printed.
Conclusion
The for loop is one of the most commonly used control structures in Java for repeated
execution. It is useful when you know the number of iterations beforehand or when you need to
iterate over arrays and collections. Understanding the for loop is essential for writing efficient
and clean Java code.
Key Points:
Standard for loop: Used when the number of iterations is known.
For loop with decrement: Useful for iterating backwards.
Multiple variables: You can use more than one variable in the initialization and iteration parts.
Nested for loops: Used for working with multi-dimensional data like matrices.
Enhanced for loop: Simplifies iterating through arrays and collections without using indices.
By using these various forms of the for loop, you can handle different types of iterations in your
Java programs efficiently.
BY: Josh