Operators

Computer Science · Java

Question 1 of 10

0

    What does this Java code print? System.out.println(16 + 6);

    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.

    Operators explained

    Java operators are symbols that combine values. Arithmetic operators such as + and % calculate new numbers, comparison operators such as == and > give true or false, logical operators such as && and || combine conditions, and assignment operators such as += change a variable's value.

    Multiplication, division and remainder are applied before addition and subtraction, and parentheses override this order. The % operator gives the remainder, and its result takes the sign of the left operand, so -7 % 3 is -1. The ++ and -- operators add or subtract one. In x++ the old value is used before the change, while in ++x the change happens first. The && and || operators short-circuit: the right side runs only when it is needed, so x != 0 && 10 / x > 1 is safe when x is 0. A common mistake is to write = where you mean ==, which assigns a value instead of comparing.

    int x = 5;
    int y = x++ + ++x;
    System.out.println(x + " " + y);
    

    Worked example

    Trace the program above.

    1. x++ uses the current value 5, and then x becomes 6.
    2. ++x changes x to 7 first, and then uses 7.
    3. y is 5+7=125 + 7 = 12, and x is 7.
    4. The output is 7 12.

    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? System.out.println(14 + 4);

    • Medium

      What does this Java code print? System.out.println(11 % 6);

    • Hard

      What does this Java code print? System.out.println(14 + 2 * 4 % 4);