</>

Technology

Java Programs

Difficulty

Beginner

Interview Question

Write a Java program to check voting eligibility using if-else (age >= 18).

Answer

If-Else Condition: Voting Eligibility

Java
public class IfElseCondition {
    public static void main(String[] args) {
        int age = 20;

        if (age >= 18) {
            System.out.println("Eligible for vote");
        } else {
            System.out.println("NOT Eligible for vote");
        }
    }
}

Output

CODE
Eligible for vote

Test with age = 15

Java
int age = 15;
// Output: NOT Eligible for vote

Nested If-Else (multiple conditions)

Java
int age = 20;

if (age < 0) {
    System.out.println("Invalid age");
} else if (age < 18) {
    System.out.println("NOT Eligible for vote (under 18)");
} else if (age < 120) {
    System.out.println("Eligible for vote");
} else {
    System.out.println("Invalid age");
}

Using Ternary Operator

Java
int age = 20;
String result = (age >= 18) ? "Eligible for vote" : "NOT Eligible for vote";
System.out.println(result);

If-Else Syntax Rules

CODE
if (condition) {
    // runs when condition is TRUE
} else {
    // runs when condition is FALSE
}
OperatorMeaning
==equal to
!=not equal to
>greater than
<less than
>=greater than or equal to
<=less than or equal to

Automation Testing Relevance

Java
// Conditional test step based on element state
if (driver.findElement(By.id("modal")).isDisplayed()) {
    driver.findElement(By.id("close-modal")).click();
    System.out.println("Modal closed");
} else {
    System.out.println("No modal, proceeding");
}

Follow AutomateQA