GeeCON Prague 2014*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt on Arrays 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 "Doubt on Arrays" Watch "Doubt on Arrays" New topic
Author

Doubt on Arrays

sukhavasi vasavi
Ranch Hand

Joined: Jul 18, 2007
Posts: 59
public static void main(String[] args) {

Object[] oa = new Object[3];

oa[0] = new Integer(1);

int i = oa[0];//3

System.out.print(i);
}
}

Why this prog shows compilation error at line 3?
While I replaced Object with int it is working .Plese Explain?
Srinivasan thoyyeti
Ranch Hand

Joined: Feb 15, 2007
Posts: 557
vasavi,

Object[] oa = new Object[3];

oa[0] = new Integer(1);

// we can't assaign Object to primitive without casting.
if (you are using 1.5) {
int i= (integer)oa[0];
else{
int i= ((integer)oa[0]).intValue();
}


Thanks & Regards, T.Srinivasan
SCWCD 1.4(89%), SCJP 5.0(75%)
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
Howdy ranchers,

in a more general view, this does not have necessarily anything to do with arrays.
More with the topic Polymorphism. When you have a polymorph variable e.g.
Object variable = new Integer(42);

Then variable is of type Object and you can perform only Object methods on it (for example hashCode() or toString());
You can never do any integer things with variable. Because a variable has a fixed type that can never changed.
But you can set up a second variable of type Integer, and refer this new variable to the Integer object (object as object, not as class Object!):
Integer i = (Integer) variable;
System.out.print(i/6);

ok, the last line requires autoboxing and won't do in java 1.4


This general issue is the base of your array question.


Hope this cleares something.

The cause why Srinivasan's code does not compile is the fact that java is CaSe sEnsItiVE.


Bu.


all events occur in real time
Srinivasan thoyyeti
Ranch Hand

Joined: Feb 15, 2007
Posts: 557
Burkhard,

Eagle eyes .
I didn't compile that.
 
GeeCON Prague 2014
 
subject: Doubt on Arrays