• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please explain this array question to me

 
Himanshu Gupta
Ranch Hand
Posts: 598
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Source cathy and sierra
chapter 3


Q7. Given:
1. class Zippy {
2. String[] x;
3. int[] a [] = {{1,2}, {1}};
4. Object c = new long[4];
5. Object[] d = x;
6. }

What is the result?
A. Compilation succeeds.
B. Compilation fails due only to an error on line 3.
C. Compilation fails due only to an error on line 4.
D. Compilation fails due only to an error on line 5.
E. Compilation fails due to errors on lines 3 and 5.
F. Compilation fails due to errors on lines 3, 4, and 5.

Answer:
A is correct, all of these array declarations are legal. Lines 4 and 5 demonstrate that arrays
can be cast.



Can someone explain me why Object c = new long[4]; is getting compiled? It should be a compile time error?
[ November 19, 2008: Message edited by: Himanshu Gupta ]
 
Graeme Jenkinson
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Although the statment new long[4] creates an array of primitives of type long, the array itself is an object. This array object is being upcast to the type Object.

Hope that makes sense to you.

thanks,

Graeme
 
Himanshu Gupta
Ranch Hand
Posts: 598
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. After all array is also an object so it can be assigned to Object reference. Thanks for your explanation.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic