devxlogo

Object Casting in Java

Object Casting in Java

In Java, objects can be cast explicitly and implicitly:

  • implicit casting happens when the source type extends or implements the target type (casting to a superclass or interface).
  • explicit casting has to be done when the source type is extended or implemented by the target type (casting to a subtype). This could produce a runtime exception (ClassCastException) if the object being cast is not of the target type.
Float floatVariable = new Float(89.0f);Number n = floatVariable; //Implicit (Float implements Number)Float secondfloatVariable = (Float) n; //ExplicitDouble doubleVar = (Double) n; //Throws exception (the object is not Double)

devx-admin

Share the Post: