Yahoo Clever wird am 4. Mai 2021 (Eastern Time, Zeitzone US-Ostküste) eingestellt. Ab dem 20. April 2021 (Eastern Time) ist die Website von Yahoo Clever nur noch im reinen Lesemodus verfügbar. Andere Yahoo Produkte oder Dienste oder Ihr Yahoo Account sind von diesen Änderungen nicht betroffen. Auf dieser Hilfeseite finden Sie weitere Informationen zur Einstellung von Yahoo Clever und dazu, wie Sie Ihre Daten herunterladen.

Java: what is the difference between j += j++; and j = j + (j + 1);?

for (i = 0, j = 0; i < 10; i++) j += j++;

System.out.println(j);

when i run this java prints the number 0 but when i type j = j + (j + 1); java prints 1023. Shouldn't I get the same outcome both times? And if not - why?

2 Antworten

Relevanz
  • Anonym
    vor 8 Jahren
    Beste Antwort

    Welcome to operations horror.

    Let's look at "j += j++" (which really looks bad)

    "j +=" is really a short way of writing "j = j +" so the calculation will actually be "j = j + j++"

    Now this looks the same as "j = j + (j+1) but nope.

    j++ is a postfix operator meaning the operation is done first, then j is incremented.

    Note also the order of operations for java says postfix (++) precedes additive (+) which precedes assignment (=).

    But postfix is done after the operation (hence the "post") so the first operation done is additive. In the first iteration, j is 0. j + j thus is 0. Now the operation is done and the postfix is evaluated next. j++ leads to j being 1 since it is currently zero. All seems good so far. Now comes assignment. But what is j assigned? Is it the result of the adding (0)? or postfix (1)? The java docs clearly state "the postfix version (result++) evaluates to the original value" so the assignment to j is given the value of j right before the postfix, that is, 0. That occurs 10 times. j at any number of iterations is therefore 0.

    Afterthought: When j++ is evaluated, the value is assigned to j before the remaining assignment (the "j = ..."). If you were to print the value of j after the postfix but before the "j = ..." you would see j is always 1 at that instance.

    Now "j = j + (j + 1)". You know brackets come first, so (j + 1) where j is originally 0 evaluates to 1. Added to 0 is again 1, and j is assigned 1. The next time, (j + 1) is 2, added to 1 is 3, etc. This line can be simplified to "j = (2j + 1)" Perform that ten times and you get 1023.

    Change the postfix to a prefix (++j) and then they are the same.

  • vor 8 Jahren

    Hi,

    j += j++; is not the same as j = j + (j +1);

    j += j++; I believe ++ will get processed first so if j was 0 it would be 1 and the 1 incremented (++) is 2 which is then added to 2 which is 4;

    Where as j = j + (j + 1) would be again assuming j was 0, it would be 0 + 1 = 1 and 1 + 1 = 2 so j would be 2.

    if your getting 1023 there is something else strange in the rest of the code.

    Hope that helps

Haben Sie noch Fragen? Jetzt beantworten lassen.