Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Casting Arrays

 
Tina Ang
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello! I'd just like to ask why the following code produces a compiler error.
double arr[] = {1.5, 2.256, 3.59};
int arr1[] = (int) arr; // compile-error
I'm confused. Please help.
Thanks,
Tina
 
Anup Engineer
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Arrays of primitive types can only be assigned to each other if their types are same:
http://www.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=012694
Please post if u learn something new while exploring this...it was a good question.
Thanks.
 
Tina Ang
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks ! But I'm still confused . In R&H page 121 (object reference casting) it was stated that "Oldtype must be an array of some type that can be cast to whatever Newtype is an array of". What does that mean?
Thanks,
Tina
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
double arr[] = {1.5, 2.256, 3.59};
int arr1[] = (int) arr; // compile-error
ok first off, you are trying to cast a double array to an int. I think it's a typo right? The "correct" code should be:
double arr[] = {1.5, 2.256, 3.59};
int arr1[] = (int[]) arr; // compile-error
(that's also the reason why it is better to put the brackets after the type and not after the identifier, int[] arr is better than int arr[])
As for why this is not possible, JLS 5.5 Casting Conversion makes it very clear:

The detailed rules for compile-time correctness checking of a casting conversion of a value of compile-time reference type S (source) to a compile-time reference type T (target) are as follows:
...
If S is an array type SC[], that is, an array of components of type SC:
...
- If T is an array type TC[], that is, an array of components of type TC, then a compile-time error occurs unless one of the following is true:
- TC and SC are the same primitive type.
...

[ March 19, 2002: Message edited by: Valentin Crettaz ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic