aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes simple one but Tricky !! 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 "simple one but Tricky !!" Watch "simple one but Tricky !!" New topic
Author

simple one but Tricky !!

sangeeta chaudhary
Greenhorn

Joined: Oct 05, 2000
Posts: 1
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

Joined: Oct 11, 2000
Posts: 2
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

Joined: Oct 11, 2000
Posts: 32
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

Joined: Sep 26, 2000
Posts: 130
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


Regards,<BR>V. Kishan Kumar
Raghvendra Sharma
Ranch Hand

Joined: Oct 09, 2000
Posts: 82
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..
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: simple one but Tricky !!