Win a copy of Testing JavaScript Applications this week in the HTML Pages with CSS and JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

Compiler error or class cast exception

 
Ranch Hand
Posts: 31
  • 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?
 
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A compiler error is generated: "incompatible types"
 
Ranch Hand
Posts: 68
  • 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.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    Bookmark Topic Watch Topic
  • New Topic