Search code examples
javaincrementpost-increment

Why does variable i not change after i=i++?


I didn't understand the below question in LinkedIn's Java Assessment Test:

for(int k =0; k<10; k=k++) {
   k+=1;
   System.out.println("Hello world.");
}

Why does this code print 10 times "Hello world."?

I know k++ means, first do job (calculate,assign,etc.) then increment k. So I think for k=k++, k must be incremented after assignment:

k=k;
k=k+1; 

which in the end, I am expecting to get k=k+1.

For example below code prints j=0 and j=1:

int j=0;
System.out.println("j=" + j++);
System.out.println("j=" + j);

Dear java experts, can you explain why k=k++ does not change k?


Solution

  • Why does this code print 10 times "Hello world."?

    No, this will be an infinite loop because the following statement resets the value of k to 1:

    k=+1;
    

    Also, k=k++ will not change the value of k because it is processed something like

    int temp = k;
    k++;
    k = temp;
    

    You can try the following code to verify this:

    int k = 1;
    k = k++;
    System.out.println(k); // Will print 1