• 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 all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Jj Roberts
  • Tim Holloway
  • Piet Souris
  • Himai Minh
  • Carey Brown
  • salvin francis

JQ+ 953425458590 (type casting)

Posts: 7
  • Mark post as helpful
  • send pies
  • 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.
brevity is the soul of wit - shakepeare. Tiny ad:
the value of filler advertising in 2020
    Bookmark Topic Watch Topic
  • New Topic