0

Could someone give me please a way to debug the following examples:

public class Example1 {
    public static void main(String[] input) {
        int i = 0;
        // i = i++ + i++;        // prints 1
        // i = i++ + i++ + i++;  // prints 3
        i = i++ + i-- + i++;     // prints 1
        System.out.print(i);
    }
}

since each example is one single line code, using a debugging is not a solution... I am trying to play with code like this one for my Java OCA 8 exam.

Thanks for your help

Janez Kuhar
  • 3,705
  • 4
  • 22
  • 45

2 Answers2

2

Lets break down your first example:

int i = 0;
i = i++ + i++;

The first i++ evaluates to 0. The new value of i is now 1. The second i++ evaluates to 1 and the new value of i is now 2. Next comes the addition of both postfix increment expressions: 0 + 1 = 1. Finally, you assign this sum to i, overwriting its temporary value (2) with the result of the sum (1).

The other examples are very similar and I leave the OP to work through them by himself.

Janez Kuhar
  • 3,705
  • 4
  • 22
  • 45
0

It is simple, just remember that post-increment unary operator uses the previous value first and then increments it, so for the next usage, the incremented value becomes the previous value and so on.

Consider this simple example;

i = 0;
j = 2 + i++; 
// j = 2 + 0 (previous value of i) i.e. 2 BUT
// i is now 0 + 1 i.e. 1 (new value of i)
System.out.println(i); // This will now print 1.
Maverick
  • 146
  • 8
  • yes but why i = i++ + i++; // prints 1... it should print 2 right? – Francesco Dassisis Feb 03 '21 at 21:50
  • Break it down. For the first i++, i = 0 is used and it increments the value for the next operation which is again i++. For this second i++, current value is 1 and hence, the sum becomes 0 + 1 = 1. Now, if you had another operation involving 'i' after this, that would have continued with the value '2'. – Maverick Feb 04 '21 at 04:16