InterviewSolution
| 1. |
Java instanceOf operator |
|
Answer» Java uses the instanceOf operator to check the type of object during the time of execution of a Java program. The instanceOf operator is used to check whether a particular object is an instance of a parent class, child class or an interface. The instanceOf operator returns a boolean value, either TRUE or false. It is used as a type comparison operator because it compares the object with its type. If APPLIED to a variable having a null value, the operator will always return a false value. For example, public class Example { public static void main(String args[]) { Example obj=new Example(); System.out.println(obj instanceof Example); } }The OUTPUT is as follows: $javac Example.java $java Example TrueHere is another example when instanceOf operator is used against a instance having null value public class Example { public static void main(String args[]) { Example obj=null; System.out.println(obj instanceof Example); } }The output is as follows $javac Example.java $java Example FalseThe instanceOf operator is also useful in downcasting. Downcasting is the process when the child class type refers to the object of the parent class. If Downcasting is performed directly, a ClassCastException is generated. The instanceOf operator PROVIDES the means for downcasting. This can be done via typecasting: class Parent { // empty class } public class Example extends Parent { static void downcast(Parent p) { if(p instanceof Example) { Example d = (Example)p; System.out.println("Downcasting SUCCESSFUL"); } } public static void main (String [] args) { Parent obj=new Example(); Example.downcast(obj); } }The output is as follows: $javac Example.java $java Example Downcasting successful |
|