OutputHard2 marks
Evaluate the Java expression: x = a * b % (++c) + (++a) + (--b); if a = 7, b = 8, c = 2
Topic: Increment / decrement operators
Previous-year question practice database
Answer
Exam answer
x = 17
Explanation
Evaluate strictly left to right, applying each prefix operator the moment it is reached, and remember that a prefix operator changes the variable BEFORE its value is used.
Start: a = 7, b = 8, c = 2
- a * b = 7 * 8 = 56
- (++c) makes c = 3, and 3 is used. So 56 % 3 = 2 (56 = 18 x 3 + 2)
- (++a) makes a = 8, and 8 is used
- (--b) makes b = 7, and 7 is used
- x = 2 + 8 + 7 = 17
Final values: x = 17, a = 8, b = 7, c = 3. The two traps are forgetting that * and % outrank +, and using the old value of a or b after the prefix operator has already changed it.
More from Revision Tour I
The full form of JVM is:2026Which of the following occupies 2 bytes of storage?2026In a statement c = c + (x * d + e); which variable is an accumulator?2026Assertion (A): The result of the Java expression 3 + 7/2 is 6.
Reason (R): According to the hierarchy of operators in Java, addition is done first followed by division.2026System.out.println('Z' + 32); will display:2025The output of 42/6%2 is:2025