File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Arrays and Object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Arrays and Object" Watch "Arrays and Object" New topic
Author

Arrays and Object

Vidhya Ramaswamy
Ranch Hand

Joined: Oct 10, 2007
Posts: 65
class Dims{
public static void main(String[] args){
1. int[] []a = {{1,2,},{3,4}};
2. Object o = a;
3. Object o1 = a[0];
4. Object o2 = a[0][0]; // how is this possible when next line is not
5. System.out.println(a[0][0] instanceof Object); /*Compile-error:
Incompatible conditional operand types int and Object*/

6. int[][] a2 = (int[][])o;
7. Integer i2 = a[0][0];
8. Integer[][] a3 = (Integer[][])o; //why ClassCastException

}
}
Could someone please explain why lines 4 and 8 behave in the way they do?
Thanks,
Vidhya
Kelvin Chenhao Lim
Ranch Hand

Joined: Oct 20, 2007
Posts: 513
Hi Vidhya,

Line 4 compiles because of auto-boxing. The primitive int from the array is automatically wrapped as an Integer object, and this is what gets assigned to the Object reference. This is the same mechanism that allows you to compile statements like "Integer x = 2;".

However, auto-boxing does not occur for instanceof tests. Hence the error for Line 5. Also, auto-boxing only applies to single primitive values, not arrays. Hence the exception on Line 8. (Note that all arrays are themselves objects, even if their elements are primitives).
[ November 18, 2007: Message edited by: Kelvin Lim ]

SCJP 5.0
Vidhya Ramaswamy
Ranch Hand

Joined: Oct 10, 2007
Posts: 65
Thanks, Kelvin.

I get it. Regarding line 8, if the original array that was assigned to the Object was an Integer array, it would have worked as follows:

Integer[][] ii = {{1,2,},{3,4}};
Object oi = ii;
Integer[][] a4 = (Integer[][])oi;

So, this has to do with downcasting. How did I not realise this earlier?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Arrays and Object
 
Similar Threads
Array Question
when is eligible for garbage collection?
Garbage collection
only 8 days for exam.....
var-args