• Post Reply Bookmark Topic Watch Topic
  • New Topic

array casting  RSS feed

 
Mukesh Prajapati
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 72
Android Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!