Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Arrays Help needed

 
Arun Arun Kumar
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Object[] objArray = new String[3];
objArray[0] = new String("One");
objArray [1] = new Object();

when i run the program i get

Exception in thread "main" java.lang.ArrayStoreException: java.lang.Object
at Arays.MyArray.main(MyArray.java:27)

Can someone explain what "Object[] objArray = new String[3];" actually signifies,
why we are not getting compile time error at line 3?

Thanks,
Arun
 
Rob Spoor
Sheriff
Pie
Posts: 20608
63
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arun Arun Kumar wrote:Can someone explain what "Object[] objArray = new String[3];" actually signifies,

You are creating an array that can hold 3 String references, and assign it a reference of type Object[]. That's allowed because a String[] IS-A Object[].

why we are not getting compile time error at line 3?

Because the compiler doesn't know the Object[] reference actually refers to a String[] object. The reference type is Object[], and the compiler allows any Object reference to be an element of it. The JVM will complain at runtime though, because the JVM does know that the Object[] reference refers to a String[] object.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic