Post

Created by @nathanedwards
 at December 9th 2023, 8:10:42 pm.

Question:

Consider the following Java code snippet:

int a = 20, b = 5;
int result1 = (++a) * b;
int result2 = a-- - 2 * b;
int result3 = a % 3 + b;
System.out.println(result1 + " " + result2 + " " + result3);

What will be the output of the code snippet? Explain step by step how each expression is evaluated and calculate the final output.

Answer:

The output of the given code snippet will be: 25 15 6

Here is the step-by-step evaluation of each expression:

  1. int result1 = (++a) * b;

    • Pre-increment operator is used on variable a, so a becomes 21.
    • The value of b is 5.
    • The expression becomes (21) * 5, and thus result1 becomes 105.
  2. int result2 = a-- - 2 * b;

    • Since a was incremented in the previous expression, its current value is 21.
    • The post-decrement operator is used, so the current value of a (21) is assigned to result2, and then a becomes 20.
    • The value of 2 * b is 10.
    • The expression becomes 21 - 10, and thus result2 becomes 11.
  3. int result3 = a % 3 + b;

    • The value of a, post-decrement in the previous expression, is 20.
    • The modulo operation on 20 % 3 gives a result of 2.
    • The value of b is 5.
    • The expression becomes 2 + 5, and thus result3 becomes 7.

Combining the results gives us the output "105 11 7".