Hi,

Pls tell me the output for the following code............

public class Test {


public static void main(String args[]){


int i=0;


for(int j=0;j<=10;j++) {


i=i++;
}


System.out.println("value of i\t"+i);
}

Dani AI

Generated

Short answer: the program prints 0. reached the correct conclusion; here is why that result is well-defined rather than a compiler quirk.

The key is Java's evaluation rules for the postfix ++ and for assignment. Conceptually the statement with the post-increment executes in three steps:

  1. The left-hand side is evaluated to produce the target variable (a reference).
  2. The right-hand side is evaluated; the postfix form yields the current value but as a side effect increments the variable storage.
  3. The assignment stores the right-hand-side value (the original value) into the target, overwriting the increment.
    Because the incremented storage is overwritten by the original value, there is no net change. In the posted loop that runs 11 times (j from 0 through 10), repeating that pattern leaves i at its initial value.

Avoid writing expressions that mix assignment and side effects in the same statement; they are easy to misread and often not what you mean. Make the increment a separate statement (or use a clear pre-increment where appropriate) so the behavior is obvious. For the formal rules see the Java Language Specification: Postfix increment operator and Evaluation order. ’s point about running the code is useful — combine quick tests with the spec explanation to learn the precise behavior.

Recommended Answers

All 3 Replies

value of i is 0(zero), because
1. the assingment to variable i has no effect.
2. i++ itself increment the value of i by one,
and againg u are trying to assing i=i++, which is no
meaning(or effect).
3. replace i=i++; with i++; it will work now.

regards,
Thiyagu.

Edit: Browser error.

why not just run it and see what happens?
Whatever happened to showing even the tiniest bit of effort and initiative?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.