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
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?