-6

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?

Kuvalya
  • 1,094
  • 1
  • 15
  • 26
  • `a=a++` has 2 steps: 1. evaluation, 2. assignment. The `++` part happens during evaluation, and then gets overwritten by the assignment – Aviad P. Jul 17 '21 at 19:24
  • 1
    Please *USE YOUR DEBUGGER*!!!! Step through the code. Look at the value of each variable at each step. I think you'll see a number of things you probably "don't expect" ;) For example, `k=+1` will assign the value "+1" ;) – paulsm4 Jul 17 '21 at 19:24
  • Short suggestion: **only use `++` in a standalone expression**. For instance, only do `i++;` and never `i = i++;`. – MC Emperor Jul 17 '21 at 19:27
  • Opps. Sorry my fault. It is k+=1; instead of k=+1;. I edited. – Kuvalya Jul 19 '21 at 23:02

2 Answers2

2

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
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
-1

It should de k+=1

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

If you want to get for k=0 => k=2

  for(int k =0; k<10; k=k+2) {
       System.out.println("Hello world.");
    }
Andreea Purta
  • 642
  • 6
  • 14