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

Compiler error or class cast exception

 
rich tana
Ranch Hand
Posts: 31
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI there
As described in the Kathy & Bert book on pg 234, will the following throw a class cast exception or generate a compiler error?

int [][] books = new int [3][];
int [] numbers = new int[6];
int aNumber=7;
books[0]=aNumber; //no since it expects an int array not int

Confusion comes into play from Chapter 3 Test question 3.
Thanks
P.S. I am sure it is an exception but as if it was C/C++, this would definitely generate a compiler error, how come Java does not follow suit?
 
Rafael Angarita
Ranch Hand
Posts: 67
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A compiler error is generated: "incompatible types"
 
sebastian tortschanoff
Ranch Hand
Posts: 68
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Rafael is right.

Here ist the Question 3 from chapter 3 (K&B):



The compiler trusts you while doing an explicit cast from o1 (which is actually a type of Object) to an int[].
This might work for the compiler cause you do it explicitly. The compiler does not know what type of object o1 is realy referencing. So he accepts, that you know.

Since "o1" is refferencing an int[][] (2-D int array) you'll get a ClassCastException at runtime. This is by the fact you did not know what you're doing and the compiler trusted you.

Would you have made "o1" refferencing to "b", which is actually an int[] array, this might work.


Youst keep in mind: The compiler does not know what o1 will be refferencing at runtime. The only thing he knows, that you have an int array "b2" and and you want to have b2 somewhen refferencing o1. You say o1 will be an int array that time. The compiler believes you and gets disappointed at runtime.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic