I am a bit flustered ....
Case 1
For the following question...
class I {
private
String name;
public String toString() {return name;}
public I(String s) {name = s;}
}
class J {
private static void m1(I[] a1) {
a1 = null;
}
public static void main (String[] args) {
I[] a1 = new I[3]; // 1
a1[0] = new I("A"); // 2
a1[1] = new I("B"); // 3
a1[2] = new I("C"); // 4
m1(a1);
for (int i = 0; i < a1.length; i++) {
System.out.print(a1[i]);
}
}
}
After method m1 returns the objects on which of the following lines are eligible for garbage collection?
a. 1
b. 2
c. 3
d. 4
e. None of the above.
f. Compiler error.
g. Run time error.
h. None of the above.
Ans : e
Reason : A copy of the refrence a1 is set to null in the method m1 but not the original .
Fine....
Case 2:
class I {
private String name;
public String toString() {return name;}
public I(String s) {name = s;}
}
class J {
private static void m1(I[] a1) {
a1[0] = a1[1] = a1[2] = null;
}
public static void main (String[] args) {
I[] a1 = new I[3]; // 1
a1[0] = new I("A"); // 2
a1[1] = new I("B"); // 3
a1[2] = new I("C"); // 4
m1(a1);
for (int i = 0; i < a1.length; i++) {
System.out.print(a1[i]);
}
}
}
After method m1 returns the objects on which of the following lines are eligible for garbage collection?
a. 1
b. 2
c. 3
d. 4
e. None of the above.
f. Compiler error.
g. Run time error.
h. None of the above.
Ans : a,b,c
Reason : Method m1 sets all elements of the array to null so the objects created on lines 2, 3 and 4 are all eligible for garbage collection when method m1 returns.
Question : Isnt a copy of the refrence to the array, passed to m1? so why should the answer be a,b,c and not e.
Case 3 :
What would be the result of this....
class I {
private String name;
public String toString() {return name;}
public I(String s) {name = s;}
}
class J {
private void m1(I[] a1) {
a1[0] = a1[1] = a1[2] = null;
}
public static void main (String[] args) {
I[] a1 = new I[3]; // 1
a1[0] = new I("A"); // 2
a1[1] = new I("B"); // 3
a1[2] = new I("C"); // 4
new J.m1(a1);
for (int i = 0; i < a1.length; i++) {
System.out.print(a1[i]);
}
}
}
After method m1 returns the objects on which of the following lines are eligible for garbage collection?
a. 1
b. 2
c. 3
d. 4
e. None of the above.
f. Compiler error.
g. Run time error.
h. None of the above.
Thanks !