Sunday, May 22, 2011

The instanceof operator in java

The instanceof operator is a binary operator that determines whether an object reference (the left operand) is an instance of the class, interface, or array type specified by the right operand. The instanceof operator cannot be used with primitive types (this results in a compilation error).

The instanceof operator returns a boolean value of true if the left operand references a non-null object of class C (or array of type T), so that at least one of the following conditions holds.
  • The right operand is a class name C' and C is a subclass of C'.
  • The right operand is an interface name I, and C implements I.
  • The right operand is an array of type T', the left operand is an array of type T, and T is a subclass or subinterface of T' or equal to T'.
The instanceof operator returns false if none of the above conditions are met or if the left operand is null.

String s = "abcd";
Vector v = new Vector();
v.add(s);
Object o = v.elementAt(0);
System.out.println(s instanceof String); // 1.true
System.out.println(s instanceof Object); //2.true
//because String is subclass of Object class
System.out.println(o instanceof String); //3.true
System.out.println(o instanceof Object); //4.true
System.out.println(o instanceof Vector); //5.false


The third output line displays a value of true even though o is declared to be of type Object. How is this so? That's because the object assigned to o is the String object that was added to Vector v.
The fourth and fifth output lines result from the fact that a String object is an Object object but not a Vector object.

No comments:

Post a Comment

Chitika