2

My question is, since new Test() is neither sub class of String or it is String itself then why instanceof compilation fails ? Shouldn't it return false.

    public class Test{
        public static void main(String[] args) {
       //Compiles fails
       System.out.println(new Test() instanceof String);
      //compiles fine but run time class cast exception.   
        Test = (Test) new Object();;
        }
    }

Now i have edited my post, So this is what i really want to know why is this difference. Why compilation not failing on casting although it should

T-Bag
  • 10,916
  • 3
  • 54
  • 118
  • 1
    What is the message of compiler? – Tatranskymedved Mar 06 '17 at 10:19
  • Compiler says- Incompatible conditional operand types TypeCasting and String – T-Bag Mar 06 '17 at 10:19
  • 1
    `Object t=new Test(); if(t instanceof String ){ }` if you say new Test() instanceof String, then you already know its not a string. instanceof works, if you are not sure, of which type the object is – XtremeBaumer Mar 06 '17 at 10:20
  • But this is why instance of operator comes into picture , I knew but logically it should show false as the result instead of compilation fails. – T-Bag Mar 06 '17 at 10:21
  • Its not duplicate please check again they are saying why there is no compilation error , I am seeking here explanation why there is error though it should be false – T-Bag Mar 06 '17 at 10:23
  • It is explained in the first duplicate proposal. – Chris311 Mar 06 '17 at 10:27
  • I have edited my question please check. – T-Bag Mar 06 '17 at 10:38

2 Answers2

5

instanceof cannot be applied if it is guaranteed at compile time to always return false.

The rule is that if casting the first operand to the type of the second operand would always throw ClassCastException, the compiler doesn't allow applying the instanceof operator on these operands.

An instance of your Test class can never be an instance of java.lang.String.

15.20.2. Type Comparison Operator instanceof

If a cast (§15.16) of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.

Community
  • 1
  • 1
Eran
  • 387,369
  • 54
  • 702
  • 768
0

The compiler knows that the type hierarchy of String is Object>String and the hierarchy of Test is Object>Test, therefore it can never be true.

Ramsay Domloge
  • 695
  • 3
  • 11