educative.io

System.out.println(x += (y-- - (x = 4) ));

how the output is 8

(y-- - (x = 4) is equal to 2

x += 2 is equal to 3


Course: https://www.educative.io/courses/basics-java-programming
Lesson: https://www.educative.io/courses/basics-java-programming/gkozn81Ly63

Hi @Amir_Mohammed !!
Sure, let’s go through the complete code step by step:

class Preincrement {
  public static void main(String[] args) {
    int x = 5;
    int y = 5;
 
    // The ++ operator changes the value 
    //  of the variable, but you can also
    //  use the result in an expression:
    
    System.out.println(x++);  // post-increment
    System.out.println(++y);  // pre-increment
    
    // assignment statements are also expressions.
    //  However, the code below is bad: it's too likely
    //  to be a typo; probably you wanted ==, the
    //  the equality comparison.
    System.out.println(x = y); 
    
    // Truly horrible programming style:
    System.out.println(x += (y-- - (x = 4) ));
  } 
}
  1. int x = 5;: Declares and initializes an integer variable x with the value 5.

  2. int y = 5;: Declares and initializes another integer variable y with the value 5.

  3. System.out.println(x++);: This line prints the current value of x, which is 5, and then increments x by 1 using the post-increment operator x++. The post-increment operator evaluates to the current value of x before the increment. So, after this line, x becomes 6.

  4. System.out.println(++y);: This line increments y by 1 using the pre-increment operator ++y and then prints the updated value of y, which is 6.

  5. System.out.println(x = y);: This line assigns the value of y (which is 6) to x, and then it prints the value of x. So, this line will print 6.

  6. System.out.println(x += (y-- - (x = 4)));: This is the most complex line in the code.

    • y--: The post-decrement operator y-- returns the current value of y, which is 6, and then decrements y by 1. So, y becomes 5, and the expression evaluates to 6.

    • (x = 4): This assigns the value 4 to x, and the expression evaluates to 4.

    • (y-- - (x = 4)): We already determined that this whole expression evaluates to 6 - 4, which is 2.

    • x += (y-- - (x = 4)): x is currently 6. The compound assignment += adds the value of the right-hand side (2) to the current value of x, making x become 8.

    • The line finally prints the value of x, which is 8.

So, the output of the complete code will be:

5
6
6
8

I hope this helps. Happy Learning :blush: