This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is Type Casting

 
Rohnit Jain
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone explain me what is typeCasting with example ?
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are telling the compiler and JVM that an object is a particular typeThe List interfce does not have an ensureCapacity method, but the java.util.ArrayList class does. So you can invoke the method on an ArrayList, not a LinkedList. So you tell the compiler that you have got an ArrayList here, and then you require space for 1000000 elements.

Note the instanceof operator ensures you have the correct type and won't suffer a ClassCastException; if you have a LinkedList, that invocation is skipped. One of the few places I like the use of instanceof.
 
Rohnit Jain
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:You are telling the compiler and JVM that an object is a particular typeThe List interfce does not have an ensureCapacity method, but the java.util.ArrayList class does. So you can invoke the method on an ArrayList, not a LinkedList. So you tell the compiler that you have got an ArrayList here, and then you require space for 1000000 elements.

Note the instanceof operator ensures you have the correct type and won't suffer a ClassCastException; if you have a LinkedList, that invocation is skipped. One of the few places I like the use of instanceof.



Its not easy example to understand, it will not become clear to undestand.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rohnit Jain wrote:Its not easy example to understand, it will not become clear to undestand.


int i = (int)16.4; what about this?

P.S.Campbell's example is clear .
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15214
36
Android IntelliJ IDE Java Scala Spring
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic