aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes parameter passing question for array reference Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "parameter passing question for array reference" Watch "parameter passing question for array reference" New topic
Author

parameter passing question for array reference

Bernd Stransky
Ranch Hand

Joined: Nov 20, 2001
Posts: 47
Hi,
following example works fine:
void m(long l) {}
....
int i=99; m(i); //numeric promotion
but why does this one not?
void m(long[] l) {}
....
int[] i={1,2,3}; m(i);
I get a compiler error message: "m(long[]) cannot be applied to (int[])"
BTW: If I use an assignment, the compiler error says 'Incompatible Types'.
I thought that assignment of arrays (which are references) work fine as long as the source type (int) can be converted to the destination type (long).
-Bernd
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
Arrays containing primitives are special and are not treated like arrays containing references.
As you already know arrays are objects in Java, thus we have to do with a widening reference conversion issue.
From JLS 5.1.4 Widening Reference Conversions

The following conversions are called the widening reference conversions:
- blablabla
- From any array type SC[] to any array type TC[], provided that SC and TC are reference types and there is a widening conversion from SC to TC.

This is the key, int and long are not reference types.


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Jennifer Wallace
Ranch Hand

Joined: Nov 30, 2001
Posts: 102
An array of references can only be converted into another array of references, if the reference types held by the arrays are convertible .
Doesnt work for primitive arrays !
Bernd Stransky
Ranch Hand

Joined: Nov 20, 2001
Posts: 47
Thank you for the info.
I guess I should start reading the JLS!
-Bernd
Bernd Stransky
Ranch Hand

Joined: Nov 20, 2001
Posts: 47
OK,
so this works:
void m(Number [] n) {}
...
Integer I[] = { new Integer(1),new Integer(2)}
m(I);
:roll: Bernd
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
yes I wonder why though
 
Don't get me started about those stupid light bulbs.
 
subject: parameter passing question for array reference