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'.
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.
I have read your blog its very attractive and impressive. I like it your blog.
ReplyDeleteJava Training in Chennai Core Java Training in Chennai Core Java Training in Chennai
This comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDelete