Java compound assignment operator: If x = 5 and y = 2, what is the value of x after executing x += y?

Difficulty: Easy

Correct Answer: x = 7

Explanation:


Introduction / Context:
Compound assignment operators in Java (like +=) combine an arithmetic operation with an assignment, improving code brevity while preserving type rules and evaluation order.


Given Data / Assumptions:

  • Initial values: x = 5, y = 2 (integers).
  • Statement: x += y which is equivalent to x = x + y.


Concept / Approach:
Evaluate x + y first, then store the result back into x. Since both x and y are ints, there is no implicit narrowing issue in this case.


Step-by-Step Solution:

Compute x + y = 5 + 2 = 7.Assign back: x = 7.Therefore, the result is 'x = 7'.


Verification / Alternative check:
In Java, x += y is exactly equivalent to x = (type of x)(x + y); with both ints, this is the same as plain addition then assignment.


Why Other Options Are Wrong:

x = 2, x = 3, x = 5, x = 10 do not reflect the addition and assignment correctly.


Common Pitfalls:

Misunderstanding compound assignment with mixed types (e.g., byte), where implicit cast occurs. Not relevant here but good to remember.


Final Answer:

x = 7

More Questions from Microprocessors

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion