File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes ArrayStoreException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of The Software Craftsman this week in the Agile forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "ArrayStoreException" Watch "ArrayStoreException" New topic


Binu K Idicula
Ranch Hand

Joined: Jul 11, 2002
Posts: 99
see this ..Can you tell me why it causes Exception when object reference can hold any instance of its subclass.
Object obj = new String("test");
obj = new Integer(3);
prints test3
But in the case of array..
Object[] obj = new String[3];
obj[0] = new Integer(3);

causes an Array Store Exception ..
Can you explain it ??
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 12913
The real type of obj is String[] therefore you can only store a String in it. If you had created the reference stored in obj as:
Object[] obj = new Object[3], it would work.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
The real type of obj is String[] therefore you can only store a String in it

obj is referencing an array of three String references.
The code is trying to place a reference to an Integer into the first element of that array. As Bill said you cannot do that.

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
It is sorta covered in the JavaRanch Style Guide.
subject: ArrayStoreException