File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Arrays Help needed Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Arrays Help needed" Watch "Arrays Help needed" New topic
Author

Arrays Help needed

Arun Arun Kumar
Greenhorn

Joined: Sep 03, 2011
Posts: 4
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

Joined: Oct 27, 2005
Posts: 19696
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Arrays Help needed