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
  • 32,711
  • 17
  • 122
  • 230
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,795
  • 5
  • 38
  • 80
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;
}
s_bei
  • 11,949
  • 8
  • 50
  • 73
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
  • 20,895
  • 3
  • 42
  • 52
1

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

mata
  • 63,859
  • 10
  • 155
  • 155
subodh
  • 6,004
  • 12
  • 48
  • 69
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
  • 125,403
  • 30
  • 199
  • 217