Win a copy of Mesos in Action this week in the Cloud/Virtualizaton 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
Pie
Posts: 48976
60
  • 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: 15286
39
Android IntelliJ IDE Java Scala Spring
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic