What is the purpose of casting in Java?
+
Casting in Java is used to convert an object from one data type to another. This is necessary when the compiler cannot automatically convert between the two types. Casting is used to ensure that the correct data type is used in a particular situation.
What is the syntax for casting an object in Java?
+
The syntax for casting an object in Java is (DataType) objectName. For example, (String) objName.
What happens if you try to cast an object to an incompatible type?
+
If you try to cast an object to an incompatible type, Java will throw a ClassCastException. This occurs when the object being cast cannot be converted to the specified type.
Can you cast an object to its own class?
+
Yes, you can cast an object to its own class. This is known as upcasting, where you are casting a subclass object to its superclass type.
What is the difference between upcasting and downcasting?
+
Upcasting is the process of casting a subclass object to its superclass type, while downcasting is the process of casting a superclass object to its subclass type.
Can you cast a primitive type to an object?
+
No, you cannot cast a primitive type to an object. However, you can use autoboxing to convert a primitive type to its corresponding object wrapper class.
What is the purpose of instanceof operator in Java?
+
The instanceof operator in Java is used to check if an object is an instance of a particular class or interface. This operator returns true if the object is an instance of the class, and false otherwise.
How do you use instanceof operator to cast an object?
+
You can use the instanceof operator to cast an object by checking if the object is an instance of the target class. If it is, you can safely cast the object to the target class.
What is the difference between explicit casting and implicit casting?
+
Explicit casting is when you use the (DataType) operator to cast an object to a specific type, while implicit casting is when the compiler automatically converts an object to a compatible type.
Can you cast an array to an object?
+
No, you cannot cast an array to an object. However, you can use the get() method of the array to retrieve an object from the array.