Conditionals

Computer Science · Java

Question 1 of 10

0

    What does this Java code print? int n = 7; if (n > 5) { System.out.println(1); } else { System.out.println(2); }

    Decimals (0.75 or 0,75), fractions (3/4) and mixed numbers (1 1/2) are accepted. Do not use thousands separators.

    How to type your answer
    • Fractions: 3/4. Mixed numbers: 1 1/2.
    • Decimals with a point or a comma: 0.75 or 0,75.
    • Negative numbers start with a minus: -3/4.
    • Percentages need the % sign: 75%.

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Conditionals explained

    In Java, an if statement runs its block only when its condition is true. else if adds further checks, and else covers every case that no earlier check matched. The condition must be a boolean expression, so writing if (x = 5) with a single equals sign, which assigns 5 to x, is a compile error for an int x. Use == to compare.

    Relational operators such as >, <=, == and != produce booleans, and they can be combined with && (and), || (or) and ! (not). Both && and || stop as soon as the result is known, which is called short-circuit evaluation. This means that in if (s != null && s.length() > 0) the second check is never run when s is null.

    Be careful with strings. The == operator on two String objects compares whether they are the same object, not whether their text matches. Use s.equals(other) to compare the text of two strings.

    int score = 72;
    if (score >= 80) {
        System.out.println("High");
    } else if (score >= 60 && score < 80) {
        System.out.println("Pass");
    } else {
        System.out.println("Retry");
    }
    

    Worked example

    Trace the code above with score = 72.

    1. Is 72 >= 80? No, so skip the first block.
    2. Is 72 >= 60 && 72 < 80? The first part is true. The second part, 72 < 80, is also true, so the whole condition is true.
    3. Print Pass and skip the else block.

    Changing the score to 85 would print High, and 50 would print Retry.

    What you will practise

    New numbers every time you practise. Levels: Easy, Medium, Hard. Each answer is followed by a worked explanation.

    Example questions

    • Easy

      What does this Java code print? int n = 6; if (n > 5) { System.out.println(1); } else { System.out.println(2); }

    • Medium

      What does this Java code print? int a = 8; int b = 2; int n = a + b; if (n > 10) { System.out.println(1); } else { System.out.println(2); }

    • Hard

      What does this Java code print? int a = 4; int b = 5; int n = a * b - 6; if (n > 20) { n = n - 10; } else { n = n + 5; } System.out.println(n);