Conditionals in Java: if, else if, switch and Worked Examples

Learn Java conditionals by tracing one student-result program from its inputs to its grade, eligibility, scholarship and lab-day outputs.

KnowledgeGate Team

Exam prep & CS education

Updated 14 Sep 20266 min read

Java programs run sequentially until a decision sends execution down one branch. With score 78, attendance 82, a submitted project and section B, Boolean checks resolve to grade B, exam eligibility, a 10% scholarship and a Wednesday lab.

1. What conditionals do in a Java program

A conditional selects a path. Use if for a one-way action, if-else for two paths, an ordered else-if ladder for ranges, and nested if for a dependent decision. Use switch for discrete alternatives and condition ? value1 : value2 for a short expression.

The example inputs are:

java
int score = 78;
int attendance = 82;
boolean projectSubmitted = true;
char section = 'B';

First predict grade B, eligibility true, scholarship 10%, and lab day Wednesday. For guided beginner courses across subjects, browse Free Courses for GATE, Placements & CS.

2. Build conditions from comparisons and Boolean operators

Comparisons produce Booleans. Here, score > 40 and score >= 40 are true, attendance < 75 is false, and attendance <= 82 is true. Use == for equality (section == 'B') and != for inequality (score != 0).

Eligibility score >= 40 && attendance >= 75 && projectSubmitted becomes true && true && true. After grading, grade.equals("A") || grade.equals("B") becomes false || true, while !projectSubmitted is false.

Java short-circuits && and ||. Here the first operand is false, so 100 / 0 is never evaluated:

java
int denominator = 0;
if (denominator != 0 && 100 / denominator > 2) {
    System.out.println("Valid ratio");
}

Propositional and Predicate Logic: Truth Tables to Proofs provides the Boolean foundation for Java's &&, || and ! expressions.

3. Start with if and if-else

java
int score = 78;

if (score >= 40) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}

The output is Pass because 78 >= 40 -> true; the else block is skipped. At the boundary, 40 prints Pass and 39 prints Fail.

A one-way if (score == 100) { System.out.println("Perfect score"); } prints nothing for 78. Use if-else for two actions. An if condition must be boolean or Boolean; an integer such as 78 is not truthy. Java Language Specification, Chapter 14 defines both if and switch, while switch uses its own supported selector types. Keep braces around single statements.

4. Choose one range with an ordered else-if ladder

java
String grade;

if (score >= 90) {
    grade = "A";
} else if (score >= 75) {
    grade = "B";
} else if (score >= 60) {
    grade = "C";
} else if (score >= 40) {
    grade = "D";
} else {
    grade = "F";
}

System.out.println("Grade: " + grade);

The output is Grade: B: Java rejects 78 >= 90, accepts 78 >= 75, and stops. Testing score >= 40 first would classify 78 as D. Boundaries are 90 -> A, 89 -> B, 75 -> B, 74 -> C, 40 -> D, and 39 -> F. One branch runs.

For a simple choice, String result = score >= 40 ? "Pass" : "Fail"; assigns Pass. Do not hide a five-grade decision inside nested ternaries; its order is harder to inspect.

Grade decision tree for a score of 78, which fails the 90 check, passes the 75 check, and resolves to grade B.

5. Combine conditions and nest only when the second decision depends on the first

boolean examEligible = score >= 40 && attendance >= 75 && projectSubmitted; reduces to true && true && true. If attendance becomes 74, the middle comparison makes the result false.

After calculating the grade, add the dependent scholarship decision:

java
int scholarshipPercent = 0;

if (examEligible && (grade.equals("A") || grade.equals("B"))) {
    if (attendance >= 85) {
        scholarshipPercent = 20;
    } else {
        scholarshipPercent = 10;
    }
}

System.out.println("Exam eligible: " + examEligible);
System.out.println("Scholarship: " + scholarshipPercent + "%");

The outputs are Exam eligible: true and Scholarship: 10%. The outer condition succeeds; 82 >= 85 fails, selecting 10. False eligibility would preserve the initial 0.

Combine independent checks with Boolean operators. Nest only when the inner question depends on the outer result. In larger programs, guard clauses or extracted methods reduce deep nesting.

6. Use switch for discrete alternatives and run the complete example

java
char section = 'B';

String labDay = switch (section) {
    case 'A' -> "Monday";
    case 'B' -> "Wednesday";
    case 'C' -> "Friday";
    default -> "Unassigned";
};

System.out.println("Lab day: " + labDay);

Selector 'B' matches the Wednesday rule, so the output is Lab day: Wednesday. Switch expressions use case ... -> rules without classic fall-through; colon-style switch statements need break to stop fall-through.

The program combines grading, eligibility, scholarship, and lab-day selection:

java
public class ConditionalsDemo {
    public static void main(String[] args) {
        int score = 78;
        int attendance = 82;
        boolean projectSubmitted = true;
        char section = 'B';

        String grade;
        if (score >= 90) {
            grade = "A";
        } else if (score >= 75) {
            grade = "B";
        } else if (score >= 60) {
            grade = "C";
        } else if (score >= 40) {
            grade = "D";
        } else {
            grade = "F";
        }

        boolean examEligible = score >= 40
                && attendance >= 75 && projectSubmitted;
        int scholarshipPercent = 0;
        if (examEligible && (grade.equals("A") || grade.equals("B"))) {
            if (attendance >= 85) {
                scholarshipPercent = 20;
            } else {
                scholarshipPercent = 10;
            }
        }

        String labDay = switch (section) {
            case 'A' -> "Monday";
            case 'B' -> "Wednesday";
            case 'C' -> "Friday";
            default -> "Unassigned";
        };

        System.out.println("Grade: " + grade);
        System.out.println("Exam eligible: " + examEligible);
        System.out.println("Scholarship: " + scholarshipPercent + "%");
        System.out.println("Lab day: " + labDay);
    }
}

It prints, in order:

Code
Grade: B
Exam eligible: true
Scholarship: 10%
Lab day: Wednesday

A colon-style switch needs break after each action. With int code = 2, cases printing B, C, then D, omitted breaks produce BCD; breaks produce B. Use switch for a discrete selector and if-else for ranges or compound rules.

Control-flow map for the worked inputs, resolving to grade B, exam eligible true, scholarship 10%, and lab day Wednesday.

7. Common errors and how exams or interviews test conditionals

Frequent mistakes include:

  • if (score = 78) assigns an int and does not compile; use score == 78.

  • if (score >= 40); ends with an empty statement, so the next block runs unconditionally; remove the semicolon.

  • An ascending ladder starting at score >= 40 gives 78 the wrong grade D; test higher thresholds first.

  • new String("A") == "A" is false because == compares references; use .equals("A").

  • Omitting braces makes later edits risky; keep braces.

  • A classic switch without break falls through, so case 2 can print BCD; add the required breaks.

Practise predicting output. The ladder gives C for 74. Changing attendance to 74 makes eligibility false and leaves scholarship at 0%. In int x = 8, y = 4; if (x > 5) if (y > 5) System.out.print("A"); else System.out.print("B");, the output is B because else associates with the nearest unmatched if.

Assessments ask you to trace branches or repair compilation, boundary and fall-through bugs. Sorting Algorithms: Complexity, Stability, n log n Bound shows the same branch logic inside comparison-based algorithms. A useful drill is to change one boundary value, predict the selected path, and then run the code.

8. Exercises, the short version and the next step

Try these exercises:

  1. Set cartTotal = 1200 and member = true. Delivery is free only when the cart condition cartTotal >= 1000 and membership are both true; otherwise deliveryFee is 99.

  2. Use conditionals to find the largest of 18, 27 and 12.

  3. Map dayNumber = 6 with switch: 1 to 5 means Weekday, 6 and 7 mean Weekend, and anything else means Invalid.

  4. Rerun the complete example with score = 91, attendance = 88, projectSubmitted = false, and section = 'C'.

The first three results are delivery fee 0, largest value 27, and Weekend. With score 91, attendance 88, projectSubmitted set to false, and section C, the modified program prints:

Code
Grade: A
Exam eligible: false
Scholarship: 0%
Lab day: Friday

Use if for one-way action, if-else for two paths, else-if for ranges, nesting for a dependent follow-up, switch for a discrete selector, and ?: for a short assignment. Continue through Java syntax and object-oriented fundamentals with the Complete Java Course. Change one input, predict all outputs, then run the program.