An if-else statement executes one group of statements when an expression is true, and another group of statements when the expression is false. In the example below, the if-else statement outputs if a number entered by the user is even or odd. The if statement executes if divRemainder is equal to 0, and the else statement executes if divRemainder is not equal to 0.
PARTICIPATION ACTIVITY
4.2.5: If-else statement: Determining if a number is even or odd
Start
2x speed
import java.util.Scanner;
Memory 95 96 1 divRemainder 97 45 userNum 98
public class EvenOdd {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int userNum;
int divRemainder;
System.out.print("Enter a number: ");
userNum = scnr.nextInt();
divRemainder = userNum % 2;
if (divRemainder == 0) {
System.out.println(userNum + " is even.");
} else {
System.out.println(userNum + " is odd.");
}
}
}