1

Possible Duplicate:
Why does this go into an infinite loop?

public class loop
{

    public static void main(String[] args)
    {
        int k=0;
        for (int i = 0; i < 6; i++) 
        {
            k = k++;
            System.out.println(k);            
        }
    }
}

out put :

0
0
0
0
0
0

Can You Please explain me why above resulting zeros even am incrementing k value and assigning it to k.

Community
  • 1
  • 1
vedamurthy
  • 11
  • 1

5 Answers5

8

This line is a no-op:

k = k++;

It's equivalent to:

int tmp = k;
k = k + 1;
k = tmp;

You're incrementing k, but then assigning the original value back to k.

I hope you don't really have code like that... while the behaviour of this code is well-defined in Java, it's (clearly) confusing.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

may be your are trying to get something like

int k=0;
    for (int i = 0; i < 6; i++) 
    {
        k = ++k;
        System.out.println(k);            

    }
Rasel
  • 15,499
  • 6
  • 40
  • 50
0

You can even better use:

for(int i = 0; i < 6; i++)
{
    System.out.println(i);
}
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
  • i wanted to know reason behind that. public class loop { public static void main(String[] rgs) { int k=0,j=0; for (int i = 0; i < 6; i++) { j= k++; System.out.println(k+" "+j); } } } – vedamurthy Jul 19 '11 at 12:57
0

The k++ piece of code increments the value of k by 1 and then returns the pre-incremented value. Thus, the following line:

k = k++;

adds one to k, and then assigns the original value of k (returned by k++) to k. This means k winds up with it's original value.

public class loop {
    public static void main(String[] args) {
        int k=0;
        for (int i = 0; i < 6; i++) {
            k++; // increments k by 1
            System.out.println(k);            
        }
    }
}
RHSeeger
  • 16,034
  • 7
  • 51
  • 41
0
public class loop
{

    public static void main(String[] args)
    {
        int k=0;
        for (int i = 0; i < 6; i++) 
        {
            k++; // k increased. No reasons to assign anything
            System.out.println(k);            
        }
    }
 }

k++ increase k, then return old k , then you asign this old k to k and k is 0 again

RiaD
  • 46,822
  • 11
  • 79
  • 123