aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Amazed that it compiles? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Amazed that it compiles?" Watch "Amazed that it compiles?" New topic
Author

Amazed that it compiles?

AKINLEYE ADEDAMOLA
Greenhorn

Joined: Sep 08, 2008
Posts: 10
this is a question from K&B chapter 3 on assignment

class Zippy
{
String []x;
int [] a[] ={{1,2},{1}};
Object c = new long[4];
Object[] d = x;
}

I compiled this and it works.
I was wondering what does new long[4] mean?I thought i ought to have a compile time error.
Hrishikesh Maluskar
Ranch Hand

Joined: Jun 19, 2008
Posts: 115
It compiles because Object is the base class of all classes and in arrays sub classes can fit into base classes.


SCJP 1.5
www.licexpadvice.com
kaushik vira
Ranch Hand

Joined: Feb 01, 2007
Posts: 102
1:- Array is one object so you can Assign it to object type variable

2:- x is instance of Object[] so you can assign x to Object[] for more clarification refer following code.

public class Test
{
int [] a[] ={{1,2},{1}};

Object c = new long[4];
/*Array is one object so you can Assign it to
object type variable*/

String [] x;
Object[] d = x;
/* x is instance of Object[] so you can assign x to Object[] for more clarification refer main()*/

public static void main(String[] args) {
String [] x = new String[1];
Object[] d = x;
if(x instanceof Object[]){
System.out.println(true);
}
}


}


kaushik Vira
-------------------------------------
SCJP, Preparing SCWCD..
AKINLEYE ADEDAMOLA
Greenhorn

Joined: Sep 08, 2008
Posts: 10
I am actually confused by the syntax new long[4]? is long[4] supposed not to mean an array with element with index 4
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

Originally posted by AKINLEYE ADEDAMOLA:
I am actually confused by the syntax new long[4]? is long[4] supposed not to mean an array with element with index 4


"new long[4]" instantiates an array object that hold 4 long values.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Hrishikesh Maluskar
Ranch Hand

Joined: Jun 19, 2008
Posts: 115
No its an Array of size 4....and Arrays are ultimately objects,so it will compile
AKINLEYE ADEDAMOLA
Greenhorn

Joined: Sep 08, 2008
Posts: 10
Oh! stupid of me to ask such question? I am used to writing new int[4] that new long[4] didn't occur to me thnxs all for the help
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Amazed that it compiles?