-4

when i am trying to compare two objects of a class it works perfectly, but it doesn't work when i am trying with some predefined class objects 'like Integer object with String object etc. want to know why it is.

2
  • 5
    Show some code. Read minimal reproducible example and How to Ask. Commented Oct 5, 2016 at 12:32
  • 3
    An Integer can never be a String. instanceof is not allowed whenever the compiler knows it will always return false. Commented Oct 5, 2016 at 12:32

2 Answers 2

1

What you mean is that something like this does not compile:

String text = "Hello";
if (text instanceof Integer) {  // Error, inconvertible types
    // ...
}

The Java compiler is smart enough to see that text is a String, which can never be an instance of Integer, so the condition would always be false - it doesn't make sense to do this kind of thing, so it's forbidden according to the rules of the Java programming language.

This is specified in paragraph 15.20.2 of the Java Language Specification, which says:

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.

Sign up to request clarification or add additional context in comments.

1 Comment

oh yeah got it thank you so much sir.....
0

Lets say you have:

Integer five = 5;
String abc = "abc";
Object fiveRef = five;
Object abcRef = abc;

fiveRef == abcRef is correct because in this case you compare two refs. and it will be true only if left and right refs to the same object;

five == abc is always false, because of different types of refs. So compiler is smart to check it.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.