I expected that in the following classes, Test would print: t is an instance of Throwable[] and that Test2 would print: t is NOT an instance of Throwable However, Test2 won't even compile. The compiler objects that they are inconvertible types. Could someone explain this please? <dl>public class Test { <dd>public static void main( String[] args ){</dd> <dl><dd>Throwable[] t = new Throwable[10];</dd> <dd>if( t instanceof Throwable[] )</dd> <dl><dd>System.out.println( <dl><dd>"t is an instance of Throwable[]" );</dd></dd></dl></dl> <dd>else</dd> <dl><dd>System.out.println( <dl><dd>"t is NOT an instance of Throwable[]" );</dd></dd></dl></dl> <dd>}</dd></dl> }</dl>
<dl>public class Test2{ <dd>public static void main( String[] args ){</dd> <dl><dd>Throwable[] t = new Throwable[10];</dd> <dd>if( t instanceof Throwable )</dd> <dl><dd>System.out.println(</dd> <dl><dd>"t is an instance of Throwable" ); </dd></dl></dl> <dd>else</dd> <dl><dd>System.out.println(</dd> <dl><dd>"t is NOT an instance of Throwable" );</dd></dl></dl></dl> <dd> } </dd> </dl>}
[This message has been edited by Brian Podolny (edited August 30, 2000).]
mehrar
Greenhorn
Joined: Aug 16, 2000
Posts: 19
posted
0
The instanceof operator is takes the left hand side as the Reference and the RHS as the type. Here type can be a class type, an array type or an interface. In case of arrays the instance of operator returns only when the array is an instance of its primitive type. But since all arrays descended from object and object array instance of returns true when we check it against each of these. Example :- String[] str = new String[10]; now str instanceof String[] ===returns true str instanceof Object ===returns true str instanceof Object[] ===returns true str instanceof String ===Compilation Error Similarly when you check :- t instanceof Throwable[] ===returns true whereas, t instanceof Throwable ===Compilation Error Hope this helps..
------------------ Raj
Raj
Brian Podolny
Ranch Hand
Joined: Aug 29, 2000
Posts: 32
posted
0
Thanks for your help but what I don't understand is WHY. Why is there a compilation error rather than the instanceof expression ( for Test2 ) simply returning false.
Originally posted by mehrar: The instanceof operator is takes the left hand side as the Reference and the RHS as the type. Here type can be a class type, an array type or an interface. In case of arrays the instance of operator returns only when the array is an instance of its primitive type. But since all arrays descended from object and object array instance of returns true when we check it against each of these. Example :- String[] str = new String[10]; now str instanceof String[] ===returns true str instanceof Object ===returns true str instanceof Object[] ===returns true str instanceof String ===Compilation Error Similarly when you check :- t instanceof Throwable[] ===returns true whereas, t instanceof Throwable ===Compilation Error Hope this helps..