This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
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

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: 12998
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.
Have you checked out Aspose?
subject: ArrayStoreException
It's not a secret anymore!