the problem is that when an array of object foo is created each object by default is null. so whenu use the instanceof operator each returns false if the objects within the array are not assigned any references of type Foo or Bar or Face.
sri chandan kalavapudi<br />SCJP 5.0<br />WORKING ON SCWCD5
first of all : instanceof Operator should be used if operand on both side are compatible. compatible means they are under same hierarchy structure.
Now understand the meaning of this :
f --> refer to one array object in the heap, and element of that array can refers to Foo or it subtype.
so if you try: f instance Foo ---> this will not compile because f refer to an array object, Foo doesn't come under hirerachy of array.
f instanceof Object --> this will compile and will give you true, because Object is superclass of array Object so under same hirerachy.
f instanceof Foo ---> This will compile and will return you false, f[i] --> can refer to Foo but currently it is null, NULL belong to every one , but doesn't refer to any one. so null instanceof anything will return you false
f isntanceof Object --> this will compile and will return you false. null belong of Object also.
f = new Foo();
f instanceof Foo ---> This will compile and will return you true
f instanceof Object ---> This will compile and will return you true, because Object is also superclass of Foo.
Originally posted by Dean Jones: When the following lines are printed,different outputs are obtained.
The output is true.
The output is false.
Can anyone please explain.
The code referred to by "line 1" returns true since an empty String to the left of "+" operator caused it to be overloaded and concatanates with null making it a String. As all objects in Java inherit from java.lang.Object the instanceof will return true.
The "line 2" however directly tests if a null reference derives from the Object or is a subclass of it however sice it does not refer to any object it by no means can be any of them. That's why the instanceof returns false.