-3

what happen in x=x++; , i need explain why x after loop still 3 #

public static void main(String[] args) {
        int x=3;
        for(int i=0;i<3;i++) {
            if(i==1) {
                x=x++;
            }
            if(i%2==0&&x%2==0) {
                System.out.print(".");
            }
            if(i%2==0&&x%2==1) {
                System.out.print("-");
            }
            if(i==2^x==4) {
                System.out.print(",");
            }

        }
            System.out.print("<");
    }

output: --,<

luk2302
  • 55,258
  • 23
  • 97
  • 137
  • NEVER use a pre-/post-increment operator on a variable and use the variable a second time in the same expression. – luk2302 Dec 19 '19 at 11:21

2 Answers2

0

The statement x++ means increment x by 1, but yield the original value of x (before the increment). In the statement x = x++, the x++ part is executed first, yielding always 3. The assignment is executed after, assigning 3 to x, so that x never changes.

Alexander van Oostenrijk
  • 4,644
  • 3
  • 23
  • 37
0

x++ post-increment means first it will use x then increment e.g

x=0 // x is 0
array[x++] = 31 // after execution of this statement x is 1.

It will store 31 in the first index of array and then increment x.

Kamil007
  • 21
  • 6