This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
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???
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.
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???
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.
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 .