File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Compiler error or class cast exception Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Compiler error or class cast exception" Watch "Compiler error or class cast exception" New topic

Compiler error or class cast exception

rich tana
Ranch Hand

Joined: Aug 25, 2008
Posts: 31
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.
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

Joined: Jan 09, 2009
Posts: 67
A compiler error is generated: "incompatible types"

Rafael Angarita.
sebastian tortschanoff
Ranch Hand

Joined: Mar 19, 2009
Posts: 68

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.

Power from within.

Failed SCJP 2 times :-(
I agree. Here's the link:
subject: Compiler error or class cast exception
It's not a secret anymore!