Using the instanceof operator to test whether a reference refers to an array. : instanceof Operator « Operators « SCJP






instanceof checks whether the object is an array.

instanceof checks whether the element type of that array is some subclass of the element type 
of the right argument. 


public class MainClass {
  public static void main(String[] argv) {
    int[] intArray = new int[2];
    if (intArray instanceof int[]) {
      System.out.println("it is an int array");
    }
    if (intArray instanceof float[]) {
      System.out.println("it is a float array");
    }
  }
}
Incompatible conditional operand types int[] and float[]








2.7.instanceof Operator
2.7.1.instanceof operator determines whether or not a given object is an instance of a particular class.
2.7.2.The instanceof operator tests the class of an object at runtime.
2.7.3.Using instanceof operator in class hierarchy
2.7.4.You cannot use a java.lang.Class object reference.
2.7.5.You cannot use a String representing the name of the class as the right operand.
2.7.6.The right operand of instanceof may be an interface.
2.7.7.Using the instanceof operator to test whether a reference refers to an array.
2.7.8.This line is not legal: if (x instanceof [])
2.7.9.Determine whether an object is an array using the isArray() method of the Class class.
2.7.10.If the left argument of the instanceof operator is a null value, the instanceof test simply returns false;
2.7.11.The instanceof Operator: Objects always "know" what type they are.
2.7.12.instanceof is for object reference variables only
2.7.13.instanceof attempts to downcast
2.7.14.test whether the null reference is an instance of a class. This will always result in false.
2.7.15.instanceof Compiler Error
2.7.16.Operands and Results Using instanceof Operator