File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question #2 from Doug's book

 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Will this code compile? If it does, what happens when it runs?
 
Yi Meng
Ranch Hand
Posts: 270
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Thomas Paul:
Will this code compile? If it does, what happens when it runs?

compiles and runs fine?
my reason: the first statements creates 10 Object reference(as an array) points to 10 null string objects. And the second statement creates an object and make array[0] (a object reference) to this object.
is this the case?
 
Cody Beth
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Thomas,
For the Code following is the explanation :
a) At compile time
1) Object[] array = new String[10];
This is fine as we can assign String to Object.
2) array[0] = new Object();
Compiler checks if array elements are of type Object.
Hence the code compiles.

b) At run-time
as "array" was initialized containing String elements so it expects that each element should always be assigned to String objects only. So the assignment is invalid.
Hence gives java.lang.ArrayStoreException
For more details refer to:
http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html#11430
 
Alton Hernandez
Ranch Hand
Posts: 443
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Thomas Paul:
Will this code compile? If it does, what happens when it runs?

Compile but won't run.
Arrays are suppose to be a collection of elements of the same type. The array in the sample code was initialized to contain String. Although its reference array was cast as Object[], this is acceptable because the type Object[] is at the top just below Object.
When an element of type Object is stored at element 0, the program throws an exception because its type is different from the initialized type of the elements of the array.
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The compiler thinks it is an array of Objects so it compiles fine. Since the array is really an array of Strings, only String objects can be placed in it. Therefore it gets a runtime java.lang.ArrayStoreException.
For more cool stuff like this: http://www.javarules.com
[ August 08, 2003: Message edited by: Thomas Paul ]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic