Junior
What is type casting in Java?
sobes.tech AI
Answer from AI
Type casting in Java is the process of converting a value of one data type to another data type.
Types of casting:
- Explicit Casting: Performed by the programmer using the
(type)operator. Used to convert from a "larger" type to a "smaller" type (e.g.,doubletoint). It may lead to data loss.// implicit casting (automatic) int a = 10; double b = a; // int to double // explicit casting (manual) double c = 10.5; int d = (int) c; // double to int, d will be 10 - Implicit Casting / Widening Conversion: Performed automatically by the JVM when converting from a "smaller" type to a "larger" type (e.g.,
inttodouble). It is safe and does not lead to data loss.int x = 10; double y = x; // int automatically cast to double
Casting can be between primitive types or between object types in an inheritance hierarchy.
When casting object types:
- Upcasting: Casting a subclass to its superclass. It is implicit and safe.
class Animal {} class Dog extends Animal {} Animal animal = new Dog(); // Upcasting - Downcasting: Casting a superclass to its subclass. It requires explicit casting and may throw a
ClassCastExceptionat runtime if the object is not actually an instance of the target subclass.Animal animal = new Dog(); // Upcasting // Downcasting - requires explicit casting and instanceof check if (animal instanceof Dog) { Dog dog = (Dog) animal; // Now you can use methods specific to Dog }