• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Doubt on Arrays

 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Ranch Hand
Posts: 558
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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();
}
 
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Srinivasan thoyyeti
Ranch Hand
Posts: 558
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Burkhard,

Eagle eyes .
I didn't compile that.
 
Roses are red, violets are blue. Some poems rhyme and some don't. And some poems are a tiny ad.
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic