wood burning stoves*
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
Author

ArrayStoreException

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");
System.out.print(obj);
obj = new Integer(3);
System.out.print(obj);
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
Rancher

Joined: Mar 22, 2000
Posts: 12761
    
    5
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.
Bill
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.
-Barry


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
 
Similar Threads
Java ---== operato
How to copy from 4 JTextFields to 1 JTextArea
confusion in if condition
Operators
initializing two dimentional objects array