title: What is the cost of casting in Java? Is it a good idea to avoid it?
body: <p>I know there are two types of casting that are <strong>implicit</strong> and <strong>explicit</strong> castings. I read different questions on the StackOverflow such as <a href="https://stackoverflow.com/questions/2165246/is-there-any-runtime-cost-for-casting-in-java">this</a>, <a href="https://stackoverflow.com/questions/8803517/performance-of-object-typecasting">this</a> and <a href="https://stackoverflow.com/questions/2170872/does-java-casting-introduce-overhead-why">this</a> but I am still wondering what is the cost of casting in Java and is it a good idea to avoid it? What is the best practice for it?</p>
  
  <p>There are 2 types of casting:</p>
  
  <pre><code>String s = "Cast";
  Object o = s; // implicit casting
  
  Object o = someObject;
  String s = (String) o; // explicit casting
  </code></pre>
  
  <p>In this second case, there is overhead in runtime, because the two type must be checked and in case that casting is not feasible, the JVM must throw a <code>ClassCastException</code>.</p>
  
  <p>Someone said it is better to profile the application to make sure casting is useful or not.</p>