aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes interesting code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "interesting code" Watch "interesting code" New topic
Author

interesting code

Parameswaran Thangavel
Ranch Hand

Joined: Mar 01, 2005
Posts: 485
hi
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++;
}
}

the output is 0.
how???
Jan Rekers
Greenhorn

Joined: Apr 09, 2005
Posts: 1
The reason that the output is zero is because of the method

void fermin(int i){
i++;
}

In this method the parameter is called i, which takes precedence over the local variable i.

Kind regards, Jan Rekers
harsha puttaswamy
Greenhorn

Joined: Mar 05, 2005
Posts: 24
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++;
}
}

i will remain 0 after the call to fermin comes back since it's original value is not affected by the increment that happens in the method fermin.

The same 0 is being assigned to i before it is being incremented since the increment is postfix.

Harsha.
Abdulla Mamuwala
Ranch Hand

Joined: Jan 09, 2004
Posts: 225
Now lets go step by step to understand how the code executes in the given program.

1> First integer i is initialized to zero i.e. int i=0.

2> We make a call to method fermin by passing i as a paramter i.e. inc.fermin(i).

3> Next in the fermin method we create a local variable i and pass the value of i above to the newly formed local variable i i.e. <B>void fermin(int i).</B>Now we increment the value of i which is a postfix increment, that is i will be incremented to 1 only the next time i is executed.

4> But in the method fermin we do not return the value of i, instead we declare fermin as void. Therefore this incremented value of i will stay as is and will not effect the value of i declared in the main method.

5>The thing to be noted is here we have two instances of the variable i one local to the method main() and the other to method fermin().

6> Now we return from the fermin and do a post increment on i i.e. i=i++.
Here the value of i should have increased to one but due to the nature of the postfix operator it does not, try replacing it with the preincrement operator and you will see the difference, i.e one will be printed if the operation was i=++1.

7> Therefore a value of zero '0' will be printed as the final result.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: interesting code