Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

interesting code

 
Parameswaran Thangavel
Ranch Hand
Posts: 485
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic