What Is Difference Between Instanceof Operator And Getclass() In Java?

2

2 Answers

Rinav Gangar Profile
Rinav Gangar answered
GetClass() method in Object Class :

String s = new String();

System.out.printl />
Returns the runtime class of an object. Here object is 's' and its type is String so it returns String

------

instanceof is a keyword.
It checks an object reference if that defined by a class or its subclasses and returns a boolean value;
The instanceof Object will return true for all object references, since all Java objects are inherited from Object. Note, that instanceof will always return false if is null.
Syntax:
instanceof ClassName

eg

dog instanceof Dog   ::   True
dalmatian instanceof Dog   ::   True
dog instanceof Dalmatian   ::   False

Hope it helps...



Broad Kenny Profile
Broad Kenny , learningslot, answered

The reason that the performance of instanceof and getClass()
== ... Is different is that they are doing different things.

  • instanceof tests
        whether the object reference on the left-hand side (LHS) is an instance of
        the type on the right-hand side (RHS) or some subtype.
  • getClass()
        == ... Tests whether the types are identical.

So the recommendation is to ignore the performance issue and
use the alternative that gives you the answer that you need.


Answer Question

Anonymous