In Java, why is instanceof
a keyword and not a method?
public static void main(String args[]) {
Simple1 s = new Simple1();
System.out.println(s instanceof Simple); // true
}
Well, there is the method Class.isInstance
... but basically it's a lower-level operation which has specific VM support, so it makes sense for it to be an operator. Aside from anything else, there's no real need to obtain the Class
reference to make the test - the bytecode can represent the operation more efficiently.
Note that you could make the same case for lots of operators... why do we need arithmetic operators rather than calling int x = Integer.add(y, z);
for example? There are benefits both in terms of convenience and performance (the latter of which a smart JIT could remove, of course) to having operators.
"instanceof" is an operator in Java and is used to compare an object to a specified type. It is provided as operator so that you can write clearer expressions.
Also isInstance is method present
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With