
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Instanceof Operator vs IsInstance Method in Java
isInstance method is equivalent to instanceof operator. The method is used in case of objects are created at runtime using reflection. General practice says if type is to be checked at runtime then use isInstance method otherwise instanceof operator can be used. See the example below −
Example
public class Tester{ public static void main(String[] args) throws ClassNotFoundException { Integer i = new Integer(10); System.out.println(usingInstanceOf(i)); System.out.println(usingIsInstance(i)); } public static String usingInstanceOf(Object i){ if(i instanceof String){ return "String"; } if(i instanceof Integer){ return "Integer"; } return null; } public static String usingIsInstance(Object i) throws ClassNotFoundException{ if(Class.forName("java.lang.String").isInstance(i)){ return "String"; } if(Class.forName("java.lang.Integer").isInstance(i)){ return "Integer"; } return null; } }
Output
Integer Integer
Advertisements