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);
}
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);
}
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:
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.
Jump to Post— jwenting 1,905why not just run it and see what happens?
Whatever happened to showing even the tiniest bit of effort and initiative?
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?
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.