Array Reference Assignments For One-Dimensional Arrays

You might also like

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 1

Array Reference Assignments for One-Dimensional Arrays

For the exam, you need to recognize legal and illegal assignments for array reference
variables. We're not talking about references in the array (in other words, array
elements), but rather references to the array object. For example, if you declare an
intarray, the reference variable you declared can be reassigned to any intarray (of
any size), but cannot be reassigned to anything that is not an intarray, including an
intvalue. Remember, all arrays are objects, so an intarray reference cannot refer to
an intprimitive. The following code demonstrates legal and illegal assignments for
primitive arrays:
int[]splats;
int[]dats=newint[4];
char[]letters=newchar[5];
splats=dats;//OK,datsreferstoanintarray
splats=letters;//NOTOK,lettersreferstoachararray
It's tempting to assume that because a variable of type byte, short, or char
can be explicitly promoted and assigned to an int, an array of any of those types
could be assigned to an intarray. You can't do that in Java, but it would be just like

those cruel, heartless (but otherwise attractive) exam developers to put tricky array
assignment questions in the exam.
Arrays that hold object references, as opposed to primitives, aren't as restrictive.
Just as you can put a Honda object in a Car array (because Honda extends Car), you
can assign an array of type Honda to a Car array reference variable as follows:
Car[]cars;
Honda[]cuteCars=newHonda[5];
cars=cuteCars;//OKbecauseHondaisatypeofCar
Beer[]beers=newBeer[99];
cars=beers;//NOTOK,BeerisnotatypeofCar

Apply the IS-A test to help sort the legal from the illegal. Honda IS-A Car, so a
Honda array can be assigned to a Car array. Beer IS-A Car is not true; Beer does not
The rules for array assignment apply to interfaces as well as classes. An array
declared as an interface type can reference an array of any type that implements the
interface. Remember, any object from a class implementing a particular interface will
pass the IS-A (instanceof) test for that interface. For example, if Box implements
Foldable, the following is legal:
Foldable[]foldingThings;
Box[]boxThings=newBox[3];
foldingThings=boxThings;
//OK,BoximplementsFoldable,soBoxISAFoldable

You might also like