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)
See also  Java Developer Jobs: Your Guide to Landing the Perfect Position in 2024
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist