• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why output 0 for this question?

 
david hu
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why output 0 for the following code?
-------------
public class Inc{
public static void main(String argv[]){
Inc inc = new Inc();
int i =0;
inc.fermin(i);
i = i++;
System.out.println(i);
}
void fermin(int i){
i++;
}
}
 
mark stone
Ranch Hand
Posts: 417
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the method fermin() returns void and secondly i is a non-static variable.
hence the line inc.fermin(i); does nothing in the line of progression of code.
next comes the line i = i++; .This line actually does something ,it increments the value of i but this incremented value (now 1) is kept in the stack. so effectively the post increment operation does increment the value for i but this value is not assigned to i.
Hence in the next statement the value of i is still 0 and is printed.
Originally posted by david hu:
why output 0 for the following code?
-------------
public class Inc{
public static void main(String argv[]){
Inc inc = new Inc();
int i =0;
inc.fermin(i);
i = i++;
System.out.println(i);
}
void fermin(int i){
i++;
}
}

 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
This has been discussed many times before. Please use the search function here at the ranch and maybe you can be helped much faster. Look here for a good explanation of the operation i = i++.
Regards,
Manfred.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic