Forums Register Login

Need help in casting topic

+Pie Number of slices to send: Send
Hi,
In the programmer's guide to java certification book i found this question:


Given the following program, which statement is true?
public class MyClass {
public static void main(String[] args) {
A[] arrA;
B[] arrB;

arrA = new A[10];
arrB = new B[20];
arrA = arrB; // (1)
arrB = (B[]) arrA; // (2)
arrA = new A[10];
arrB = (B[]) arrA; // (3)
}
}

class A {}

class B extends A {}

Select the one correct answer.

a.The program will fail to compile because of the assignment at (1).

b.The program will throw a java.lang.ClassCastException in the assignment at (2) when run.

c.The program will throw a java.lang.ClassCastException in the assignment at (3) when run.

d.The program will compile and run without errors, even if the (B[]) cast in the statements at (2) and (3) is removed.

e.The program will compile and run without errors, but will not do so if the (B[]) cast in statements at (2) and (3) is removed

The answer was c.
why? please help.

Thank you.
+Pie Number of slices to send: Send
An array itself is an Object, and thus, you try to cast an Object as B[] will encounter ClassCastException.

Nick
+Pie Number of slices to send: Send
For the same reason as in the following code snippet (without arrays) :-

A myA;
B myB;
myA = new A();
myB = (B)myA; // ClassCastException is thrown here

Compile Time Rule :- When oldType and newType are classes, one class must be the subclass of another, no matter which one.. For this reason, the compilation succeeds in above code.

Run Time Rule :- When newType is a class, the class of the expression being converted must be newType or must inherit from newType.. Here the class of the expression being converted is A which is neither B nor inherits from B. Therefore the ClassCastException at run time.


Similarly, for Arrays :-

Compile Time Rule :- When both oldType and newType are arrays, both arrays must contain reference types (not primitives) and an element of one type must be same or subclass of the element of another type, no matter which one.

Run Time Rule :- The element of the type being converted (oldType..i.e., the actual object type it refers to) must be same as or subclass of the element of the newType otherwise ClassCastException

HTH
+Pie Number of slices to send: Send
Thank you Rupak Khurana and Nicholas Cheung.
You ought to ventilate your mind and let the cobwebs out of it. Use this cup to catch the tiny ads:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 728 times.
Similar Threads
Ques on casting referances ...
Reference Casting
Arrays
ClassCastException??
Question on Casting
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 03:39:00.