What is type casting? Explain up casting vs down casting?

What is type casting? Explain up casting vs down casting? When do you get ClassCastException?

The conversion of a given expression from one type to another type is referred as ‘type casting’.

Upcasting refers to converting lower to upper such as giving subclass reference to super class.

Down casting refers to converting upper to lower, such as giving super class reference to subclass.

ClassCastException is thrown when an invalid cast occurs. It indicates that the application has attempted to cast an object to a subclass which is not the object’s instance. It also occurs when an attempt is made to insert an incompatible object to a collection.

What is type casting? Explain up casting vs down casting? When do you get ClassCastException?

Changing a type of a value from one type to another type is called type casting.

Example:
int i =10;
float x = (float) i;

The concept of upcasting and down casting is related to the classes.
Example:
Parent p = new Child();
Different types of inner classes in Java
There are 4 types of inner classes - Member inner class, Local inner class, Static inner class and Anonymous inner class...
What are packages in Java?
What are packages in Java? - Package is a collection of classes that avoids name space collision...
What are Native methods in Java?
Java Native methods - Java applications can call code written in C, C++, or assembler. This is sometimes done for performance.....
Post your comment