Java Selection Statements Demystified: Exploring if, if-else, and switch Statements with Problem Examples

Java Selection Statements

JavaFar Academy - Learn to Code with Java & PythonJavaFar Academy - Learn to Code with Java & Python

Java selection statements control the execution flow based on conditions. Java selection statements are:

The if-else statement lets you run particular code blocks based on a Boolean condition. If the condition evaluates to true, the block inside the if part executes. Otherwise, the code inside the else part (if present) executes.

Example Problem: Checking if a number is positive or negative.

public class PositiveNegative < public static void main(String[] args) < int number = -5; if (number >0) < System.out.println(number + " is positive."); >else if (number < 0) < System.out.println(number + " is negative."); >else < System.out.println("The number is zero."); >> > 

Using the if-else statement, this program checks if a number is positive or negative.

The switch statement allows you to select one of many code blocks to be executed based on the value of a variable or expression. It’s a cleaner alternative to using multiple if-else statements when comparing the same variable against multiple values.

Example Problem: Day of the Week

public class DayOfWeek < public static void main(String[] args) < int day = 4; // 1: Monday, 2: Tuesday, . 7: Sunday 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"); >> > 

This program uses the switch statement to print the name of the day of the week based on its numerical value.

Conclusion

Java if-else and switch statements control execution flow based on conditions or values. The choice between using an if-else statement or a switch statement often depends on your program’s specific needs and code clarity.

Reference Links to Include:

  1. Oracle’s Java Documentation:
  2. Java Programming Tutorials by Oracle:
  3. GitHub Java Projects:
  4. Stack Overflow for Java Programming Questions: