FAQ

Java

JSP

Servlet


Advertisement



Can an array of primitive types be casted to an array of object reference?

You can have

Object c = new long[4];    //case 1
Object[] c1 = new Long[4]; //case 2

but you can not have

Object[] c = new long[4];  //case 3

When you create an array of type primitive and the elements of it are primitives. eg. long[] l = new long[3];, you create one array object and its three primitives element initialized to 0. But when you create an array of any java Object, eg. String[] sa = new String[3];, you create one array object and three references initially pointing to 'null'.

An array is an Object, a reference to an array can be converted to a reference of type Object.

Object c1 = new long[4];
Object c2 = new Long[4];

A reference of an array of type reference can cast to a reference of an array of type Object, because any reference object is sublcass of Object. For example, Long is-a Object, an instance of array of type Long can implicitly convert to an array of type Object:

Object[] c = new Long[4];

A reference of an array of type primitive can not be cast to a reference to an array of type Object. Because the elements of an array of type primitive are primitives and cannot be upcasted to Object. Also, you can't convert or cast an array of primitive to an array of different primitive. They are two different types and the compiler is complaining: "Incompatible arg type". The automatic widening or narrowing does not apply to array types as if it works for primitive types.

Object[] c = new long[4];  //compile time error
int[] ia1={1,2};
long[] la1 = {2,3};
la1 = ia1; // compiler error
long[] la2 = new int[4]; // compiler error

int[] ia2;
ia2 = ia1; //OK


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |