Saturday 14 June 2014

Array Store Exception

For an array whose type is A[], where A is a reference type, an assignment to a component of the array is checked at run time to ensure that the value being assigned is assignable to the component.

If the type of the value being assigned is not assignment-compatible with the component type, an ArrayStoreException is thrown.



  • The variable pa has type Point[] and the variable cpa has as its value a reference to an object of type ColoredPoint[]. 
  • A ColoredPoint can be assigned to a Point; therefore, the value of cpa can be assigned to pa.
  • A reference to this array pa, for example, testing whether pa[1] is null, will not result in a run-time type error. 
  • This is because the element of the array of type ColoredPoint[] is a ColoredPoint, and every ColoredPoint can stand in for a Point, since Point is the superclass of ColoredPoint.
  • On the other hand, an assignment to the array pa can result in a run-time error. At compile time, an assignment to an element of pa is checked to make sure that the value assigned is a Point. 
  • But since pa holds a reference to an array of ColoredPoint, the assignment is valid only if the type of the value assigned at run time is, more specifically, a ColoredPoint. 
  • The Java Virtual Machine checks for such a situation at run time to ensure that the assignment is valid; if not, an ArrayStoreException is thrown.

No comments:

Post a Comment