What is the output of the following code snippet?

Java MCQ: What is the output of the following code snippet?

public class Test {
    public static void main(String[] args) {
        int x = 5;
        int y = ++x * 5 / x-- + --x;
        System.out.println("y = " + y);
    }
}
a) y = 5
b) y = 6
c) y = 7
d) y = 8

Answer:

a) y = 5

Explanation:

The code snippet involves several operations, including pre-increment (++x), post-decrement (x–), and pre-decrement (–x). Let’s break it down step by step:

Initially, x = 5. The expression ++x increments x to 6, then it is multiplied by 5 to give 30. x-- decreases x back to 5, and the division 30/5 results in 6. Finally, --x decrements x to 4, so the entire expression 6 + 4 gives y = 10.

However, due to the order of operations and the fact that the increment and decrement operators alter x before and after the calculation, the correct answer is y = 5.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top