Thursday, October 22, 2015

Instanceof Keyword


It is very common, when we get ClassCastException. To get over this, we have instanceof keyword.

instanceof keyword is use to check the object is a instance of specified type.

if (objectReference instanceof type)
The following if statement returns true.

public class TryCatch {
public static void main(String[] args) {

String name = null;
if (name instanceof java.lang.String) {
System.out.println("True");
} else {
System.out.println("False");
}
}

}

Above code will print True.


When we apply instanceof on a null variable, it returns False. Below is the code sample for reference.

public class TryCatch {
  public static void main(String[] args) {

    String name = null;
    if (name instanceof java.lang.String) {
      System.out.println("True");
    } else {
      System.out.println("False");
    }
  }

}


Is a child class also the instance of parent class? Answer is Yes and to prove this refre to the below code.

class Vehicle {

public Vehicle(){

}

}

class Car extends Vehicle {

public Car(){

super();
}

}


public class TryCatch {
public static void main(String[] args) {

Car car = new Car();
if (car instanceof Vehicle) {
System.out.println("True");
} else {
System.out.println("False");
}

}

}



No comments:

Post a Comment

Thank you for your comments.