File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes array casting Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "array casting " Watch "array casting " New topic
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
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: array casting
 
Similar Threads
Event Handlers:Mouse over "circles"
HashSet issue
casting primitive arrays
Question on collections framework in java
Why is this code giving compilation error on red line?