File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt on Arrays" Watch "Doubt on Arrays" New topic

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


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

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];
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;

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.


all events occur in real time
Srinivasan thoyyeti
Ranch Hand

Joined: Feb 15, 2007
Posts: 557

Eagle eyes .
I didn't compile that.
I agree. Here's the link:
subject: Doubt on Arrays
It's not a secret anymore!