SCJP 6 Questions: Pass by reference with example
See the code:
class GFC304 {
static void m1(int[] i1, int[] i2) {
int[] i3 = i1;
i1 = i2;
i2 = i3;
}
public static void main (String[] args) {
int[] i1 = {1}, i2 = {3};
m1(i1, i2);
System.out.print(i1[0] + "," + i2[0]);
}}
What will be the output?
Answer: 1,3
Explanation: Here we are passing the copy of reference variables
i1 and i2 from main() method to method m1(). Now m1 has it's own
local reference variables i1 and i2 referring to same array as main()
method's i1 and i2. So you can see that we are only passing the
reference variables not exactly the value they are refering.
See this figure...
Now see the second code.......
class GFC305 { static void m1(int[] i1, int[] i2) { int i = i1[0]; i1[0] = i2[0]; i2[0] = i; } public static void main (String[] args) { int[] i1 = {1}, i2 = {3}; m1(i1, i2); System.out.print(i1[0] + "," + i2[0]); }}
What will be the output?
Answer: 3,1
Explanation: Here in the m1() method we are passing the exact reference
containing array (i[0] and i2[0]) not the copy of reference variable(i1,i2).
See the figure...
Comments
Post a Comment