aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes why output 0 for this question? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "why output 0 for this question?" Watch "why output 0 for this question?" New topic
Author

why output 0 for this question?

david hu
Ranch Hand

Joined: Jul 20, 2001
Posts: 143
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

Joined: Dec 18, 2001
Posts: 417
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

Joined: Jan 09, 2001
Posts: 1492
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.
 
jQuery in Action, 2nd edition
 
subject: why output 0 for this question?