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 Answers
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
instanceofrelational expression likewise produces a compile-time error. In such a situation, the result of theinstanceofexpression could never be true.
1 Comment
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.
instanceofis not allowed whenever the compiler knows it will always return false.