• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Example for Casting

 
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
From JLS:
The detailed rules for compile-time correctness checking of a casting conversion of a value of compile-time reference type S (source) to a compile-time reference type T (target) are as follows:
One of the rules goes something like :
If S is a class type then:
If T is an array type, then S must be the class Object, or a compile-time error occurs.
Can someone please suggest an example that goes with the above rule?
 
Wanderer
Posts: 18671
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Let's say you're using a Vector to store several arrays. You may find it necessary to do something like:
<code><pre> int[] nextArray = (int[]) myVector.elementAt(0);</pre></code>
This is necessary because the elementAt() method is declared to return an Object. To use that Object as an array, you need to cast it to the appropriate type. This is OK at compile time because the compiler knows that an Object could be an array. At run time, we will find out whether the object in question really is an array - if not, a compile error occurs.
On the other hand, let's say you tried to do something like this:
<code><pre> int[] array = (int[]) someObject.toString();</pre></code>
The compiler will stop you right away, because there is no way that any String returned by toString() could possibly be an array. No need to wait for runtime - we already know it's impossible.
 
Surya B
Ranch Hand
Posts: 98
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Jim for the answer,the concept is clear to me now.
 
Whoever got anywhere by being normal? Just ask this exceptional tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic