Hi guys!!,
Can u pls help me in coping up with following doubts
these are from K & B book,Chapter 3,self
test)
1:Given:
class CardBoard {
Short story = 5;
CardBoard go(CardBoard cb) {
cb = null;
return cb;
}
public static void main(
String[] args) {
CardBoard c1 = new CardBoard();
CardBoard c2 = new CardBoard();
CardBoard c3 = c1.go(c2);
c1 = null;
// do Stuff
} }
When // doStuff is reached, how many objects are eligible for GC?
A. 0
B. 1
C. 2
D. Compilation fails.
E. It is not possible to know.
F. An exception is thrown at runtime.
Ans: C is correct. Only one CardBoard object (c1) is eligible, but it has an associated Short wrapper object that is also eligible.
Doubt: C1 is referenced by C3 then how can it be eligible for GC. And if u say,that it is, than why not C2..
2:Given:
1. class Dims {
2. public static void main(String[] args) {
3. int[][] a = {{1,2,}, {3,4}};
4. int[] b = (int[]) a[1];
5. Object o1 = a;
6. int[][] a2 = (int[][]) o1;
7. int[] b2 = (int[]) o1;
8. System.out.println(b[1]);
9. }
10. }
What is the result?
A. 2
B. 4
C. An exception is thrown at runtime.
D. Compilation fails due to an error on line 4.
E. Compilation fails due to an error on line 5.
F. Compilation fails due to an error on line 6.
G. Compilation fails due to an error on line 7.
Ans:C is correct. A ClassCastException is thrown at line 7 because o1 refers to an int[][] not an int[]. If line 7 was removed, the output would be 4.
Doubt: We know that "If you assign an array to a previously declared array reference, the array you're assigning must be the same dimension as the reference you're assigning it to."
But in this Question at line 5 : Object o1 = a;Are we not assigning anything here???
Or, does this mean that we are creating an Object type of object which is referring to the same array object as 'a' on heap.
3: Given:
1. class Zippy {
2. String[] x;
3. int[] a [] = {{1,2}, {1}};
4. Object c = new long[4];
5. Object[] d = x;
6. }
What is the result?
A. Compilation succeeds.
B. Compilation fails due only to an error on line 3.
C. Compilation fails due only to an error on line 4.
D. Compilation fails due only to an error on line 5.
E. Compilation fails due to errors on lines 3 and 5.
F. Compilation fails due to errors on lines 3, 4, and 5.
Ans: A is correct, all of these array declarations are legal. Lines 4 and 5 demonstrate that arrays can be cast..
Doubt: How come line 4: Object c = new long[4];
is correct because there are no square brackets on left side of the expression...Is it the correct syntax for an array???
Please help me out....
Thanks
Swapnil
[ June 15, 2006: Message edited by: Swapnil Trivedi ]