Casting an array versus casting its elements

A Java media application uses these class declarations:


Java
class Asset {}
class Photo extends Asset {}
class Audio extends Asset {}


Each labelled case below runs independently inside a method, starting with fresh variables. Classify what happens when its two statements execute.


Typed array:


Java
Asset[] items = new Photo[2];
Photo[] photos = (Photo[]) items;


Broad array:


Java
Asset[] items = new Asset[] {new Photo(), new Photo()};
Photo[] photos = (Photo[]) items;


Single element:


Java
Asset[] items = new Asset[] {new Photo(), new Photo()};
Photo photo = (Photo) items[0];


Different asset:


Java
Asset[] items = new Photo[2];
items[0] = new Audio();


Null element:


Java
Asset[] items = new Photo[2];
items[0] = null;


Enter exactly OK if both statements complete normally, CAST if execution throws ClassCastException, or STORE if execution throws ArrayStoreException. All five cases compile.

CaseOutcome
Typed array
Broad array
Single element
Different asset
Null element

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Type Conversion and Casting Questions: