Submitted by: Octavia Anghel(octaviaanghel@gmail.com)

Wednesday Oct 31st 2018 by Octavia Anghel

Language: Java, Expertise: Beginner - See how objects can be cast explicitly and implicitly 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; //Explicit
Double doubleVar = (Double) n; //Throws exception (the object is not Double)
Mobile Site | Full Site