Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, why is instanceof a keyword and not a method?

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
}
like image 580
Atul Kumar Khare Avatar asked Nov 20 '15 10:11

Atul Kumar Khare


2 Answers

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.

like image 156
Jon Skeet Avatar answered Sep 19 '22 10:09

Jon Skeet


"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

like image 25
Ankur Singhal Avatar answered Sep 23 '22 10:09

Ankur Singhal