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

simple one but Tricky !!

 
sangeeta chaudhary
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What will be the o/p of this code ???
public class Inc{
public static void main(String argv[]){
Inc inc = new Inc();
int i =0;
inc.fermin(i);
int y = i++;
System.out.println(y);
System.out.println(i);
}
void fermin(int i){
i++;
}
}
answer is 0 . Why???
 
Jatinip
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The int passed to the method call is actually the copy of int declared in the main method. Incrementing the int in the method does not change its value in the main.
 
Mukesh Rathod
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In java, the argument is passed to method call using passed by value only. Hence, a copy of variable is passed to the method called, so any change in this copy, will not have any effect on the original variable.
In the given example, the variable name i in the method fermin used to create confusion only. Actually this varible i is the local copy of the method and hence its scope is limited to the method only. It just hold the copy of value passed by the method call and hence no relation with the i in main method.
Mukesh
Originally posted by sangeeta chaudhary:
What will be the o/p of this code ???
public class Inc{
public static void main(String argv[]){
Inc inc = new Inc();
int i =0;
inc.fermin(i);
int y = i++;
System.out.println(y);
System.out.println(i);
}
void fermin(int i){
i++;
}
}
answer is 0 . Why???

 
Kishan Kumar
Ranch Hand
Posts: 130
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sangeetha,
The answer is
0
1
right.
That is becuase y = i++ will assign value of i to y and then i
gets incremented. The value of y is still 0 but the value of
i is 1. Is this what you want. If you are concerned about
parameter passing then i think jatinip and mukesh have given
nice explanations.

------------------
Regards,
V. Kishan Kumar
 
Raghvendra Sharma
Ranch Hand
Posts: 82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Sangeeta,
The answer should be
0
1
when you are passing i to the function, a copy of i goes and the original i remains as such. The changes to the i (inside the function ) doesn't affect the original i.
so when the function comes back it finds the original i at 0 and resumes from there .

Hope it helps.
raghav..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic