wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Casting Arrays Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Casting Arrays" Watch "Casting Arrays" New topic
Author

Casting Arrays

Tina Ang
Ranch Hand

Joined: Mar 12, 2002
Posts: 58
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

Joined: Mar 04, 2002
Posts: 48
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.


Anup Engineer
Tina Ang
Ranch Hand

Joined: Mar 12, 2002
Posts: 58
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

Joined: Aug 26, 2001
Posts: 7610
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 ]

SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Casting Arrays