• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

JQ+ 953425458590 (type casting)

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello all,
On JQ+ there is a question as follows:
public class TestClass
{
public static void main(String args[])
{
A[] a, a1;
B[] b;
a = new A[10]; a1 = a;
b = new B[20];
a = b; // 1
b = (B[]) a; // 2
b = (B[]) a1; // 3
}
}
class A { }
class B extends A { }
..............
The choices are
1) Compile Time error at line 3
2) The program will throw java.lang.ClassCastException at line 2 when run
3) The program will throw java.lang.ClassCastException at line 3 when run
4) The program will compile and run, if the (B[]) cast at line 2 and the whole line 3 is removed
5) The cast at line 2 is needed
..............
The answers are 3 and 5. I don't quite understand why it will throw a ClassCastException at line 3 if it does not do so at line 2. If I had variables A a = new A(); and B b = new B(), a = b does not need a cast, but b = a would not work. b = (B) a is required. The only thing I can see causing the specified behaviour is line 1, but I don't understand why it is so. Can someone please clarify this for me? Thanks.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic