Java If...Else Examples: Conditional Logic in Action

Explore practical examples of the if...else statement in Java, a fundamental control structure for implementing conditional logic. In the first example, learn how to open a door with a specific code using an if statement to validate the input. See how to effectively use if...else to execute different actions based on conditions, enhancing your programming skills in Java.



Java If...Else Examples

Example 1: Opening a door with a code

int doorCode = 1337;

if (doorCode == 1337) {
  System.out.println("Correct code. The door is now open.");
} else {
  System.out.println("Wrong code. The door remains closed.");
}

Explanation: In this example, we check if the doorCode matches the correct code (1337). If it does, the message "Correct code. The door is now open." is printed. Otherwise, if the code is incorrect, the message "Wrong code. The door remains closed." is printed.


Example 2: Checking if a number is positive or negative

int myNum = 10;

if (myNum > 0) {
  System.out.println("The value is a positive number.");
} else if (myNum < 0) {
  System.out.println("The value is a negative number.");
} else {
  System.out.println("The value is 0.");
}

Explanation: Here, we determine whether myNum is positive, negative, or zero using if...else if...else statements. Depending on the value of myNum, the appropriate message is printed.


Example 3: Checking if a person is old enough to vote

int myAge = 25;
int votingAge = 18;

if (myAge >= votingAge) {
  System.out.println("Old enough to vote!");
} else {
  System.out.println("Not old enough to vote.");
}

Explanation: This example checks if myAge is greater than or equal to votingAge (18). If true, it prints "Old enough to vote!". Otherwise, it prints "Not old enough to vote.". This demonstrates how if...else statements can be used for decision-making based on conditions.


Example 4: Checking if a number is even or odd

int myNum = 5;

if (myNum % 2 == 0) {
  System.out.println(myNum + " is even");
} else {
  System.out.println(myNum + " is odd");
}

Explanation: Here, we use the modulus operator (%) to check if myNum is even or odd. If the remainder when divided by 2 is 0, it prints "myNum is even". Otherwise, it prints "myNum is odd". This showcases how if...else statements can be used to perform different actions based on the result of a condition.