| Author |
array casting
|
Mukesh Prajapati
Greenhorn
Joined: Feb 02, 2011
Posts: 10
|
|
public class MainClass {
public static void main(String[] argv) {
int sizes[] = { 4, 6, 8, 10, 14, 20 };
Object obj = sizes;
int x = ((int[]) obj)[2];
}
}
please explain me above red lines
|
 |
Suhas Mandrawadkar
Ranch Hand
Joined: Jul 21, 2007
Posts: 72
|
|
Line 1:Arrays are objects in Java. Hence they can be assigned to Object references.
Line 2: Object reference is type casted back to int array and element in [2] array position is assigned to int x.
|
Regards, Suhas S. Mandrawadkar.
Certifications: SCJP 6, SCWCD 5, Oracle WebLogic Server Administrator, OCE Java EE 6 EJB Developer
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Object obj = sizes;
Any array is also an object. That means that you can use widening to assign the array reference to an Object reference.
int x = ((int[]) obj)[2];
This looks complex for the beginning programmer, so let's split it up:
(int[]) obj casts the Object reference back to an int[] reference.
((int[]) obj) simply adds a pair of parentheses because of operator precedence. The result is now an int[].
((int[]) obj)[2] takes that int[], and then gets the third element of it.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: array casting
|
|
|