0

Java Code below :

    int x = 10;
    while (x != 15){
       x = x++;
       System.out.println("Value X " + x);
    }

execute : endless Loop ? why ?

Junior
  • 19
  • 3

6 Answers6

2

Because x will never change and always will be 10. Read JLS.

Andremoniy
  • 34,031
  • 20
  • 135
  • 241
2

I may be wrong but x++ incrementes x after reading it so x = x++ means x = x. You should use x = ++x instead.

See this question

Community
  • 1
  • 1
StepTNT
  • 3,867
  • 7
  • 41
  • 82
2

Becouse you assign the old value of x to x befor you increase the value! Try this:

int x = 10;
while (x != 15){
   x++;
}

or

int x = 10;
while (x != 15){
   x = ++x;
}
nano_nano
  • 12,351
  • 8
  • 55
  • 83
1

x++; increments the value of x then returns the old value of x.

THEN x = (that number) executes, meaning the mutation x++ did of x is undone.

Patashu
  • 21,443
  • 3
  • 45
  • 53
1

The line x = x++; should be x++;

mata
  • 67,110
  • 10
  • 163
  • 162
subodh
  • 6,136
  • 12
  • 51
  • 73
0

Because x = x++ will assign the result of the operation x++ to x. What you want is only x++;, which increments the value of x by one.

David Hedlund
  • 128,221
  • 31
  • 203
  • 222