Greetings, Java explorers!
In today’s session, we delve into the heart of decision-making in Java programming: conditional statements. These structures allow your program to make choices based on specific conditions, leading to dynamic and responsive code.Let’s unravel the mysteries of if, else if, else, and switch statements in Java.
1. if Statement
The if statement is the most basic form of control structure. It executes a block of code if a specified condition is true.Example:
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
}
2. else if Statement
The else if statement is used to specify a new condition if the first condition is false.Example:
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
}
3. else Statement
The else statement is used to execute a block of code if all the preceding conditions are false.Example:
int number = 0;
if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
4. switch Statement
The switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.Example:
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
// ... other cases ...
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}
Exercise:
Using Conditional StatementsNow, it’s your turn to practice. Write a Java program that uses conditional statements to:Determine if a number is positive, negative, or zero.Display the name of the day based on a number (1 for Monday, 2 for Tuesday, etc.).
Conclusion
Great job on completing this session! Conditional statements are crucial in programming, allowing your code to make decisions and react differently under various conditions.Keep practicing these concepts to master control structures in Java. They are key to making your programs more logical and powerful.Looking forward to seeing your progress in Java programming. Happy coding!