Java – Different methods for casting an object in Java

castingjava

I know the three following methods that can be used for casting objects.

Object o = "str";

String str1 = (String) o;                // Method 1

String str2 = o.toString();              // Method 2

String str3 = String.class.cast(o);      // Method 3
  1. Which approach is better, and what are the pros/cons of one method as compared to the others?
  2. What happens to the object during the time of casting internally?

Best Solution

The second method that you show is not casting; it's simply calling the toString() method on an object, which is not different than any other method call:

String str2 = o.toString();

The effect of the first and third methods is essentially the same. I would prefer using the first method.

What happened with object on the time of casting internally?

Nothing happens to the object. Casting is not a way to somehow automatically convert objects from one type to another type. The only thing that a cast does, is tell the compiler to accept the assignment statement and not check the types for this statement. You're saying to the compiler "I know better than you what kind of object this is, so let me do this assignment and don't complain about the type".

In your example, the type of the variable o is Object. When you assign o to a variable of type String, the compiler won't allow it because it checks the types, and it can't be sure that o in fact refers to a String object. So you use a cast to tell the compiler "I know this is a String object, so let me do this assignment".

The type will still be checked, but at runtime, not at compile time. If, at runtime, the type of the object is not String, you'll get a ClassCastException.