Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ArrayStoreException

 
Binu K Idicula
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13055
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic