Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Integer is subclass of object

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know that Integer is a subclass of Object. Therefor it is possible to transfer an collection element from get(Object o) to Integer with (Integer) lst.get(elementnr).
Please consider this code:
class XTC {
public static void main ( String [ ] ka ) {
Integer b = null ;
System.out.println( b instanceof Object ) ; //prints false
Integer c = new Integer(2);
System.out.println( c instanceof Object ) ; //prints true
}
};
Why is Integer b = null; System.out.println(b instanceof Object) printing false?
Appreciate your answers.
Thomas
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"null instanceof X" is false for any X.
[ November 01, 2002: Message edited by: Ron Newman ]
 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
JLS 15.20.2 Type Comparison Operator instanceof
The type of a RelationalExpression operand of the instanceof operator must be a reference type or the null type; otherwise, a compile-time error occurs. The ReferenceType mentioned after the instanceof operator must denote a reference type; otherwise, a compile-time error occurs.
At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast (�15.16) to the ReferenceType without raising a ClassCastException. Otherwise the result is false.
If a cast 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.
 
Michael Zalewski
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The instanceof operator compares types at run-time. It does not compare the type of the variable as declared in the program.
Your example of Integer class kind of confuses things because Integer is final, so it can't have subclasses.
But say you had this:

It should print out:

What you should find interesting is the second line. The variable n1 is declared as a Number. but n1 instanceof Integer still returns true.
That's because instanceof looks at the run time type of the operand.
So the answer to your question is:
null instanceof Integer returns false because the operand null does not have any type. "null" is not an Integer or any of its subclasses, so null instanceof Integer returns false.
[ November 01, 2002: Message edited by: Michael Zalewski ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic