Test object type in java

Java instanceof Operator

Java instanceof operator (also called type comparison operator) is used to test whether the specified object is an instance of the specified type (class, subclass, or interface).

  • true – if the variable is an instance of the specified class, its parent class or implements specified interface, or its parent interface
  • false – if the variable is no instance of the class or implement the interface, or the variable is null.
HashMap map = new HashMap(); assertTrue( map instanceof Map ); assertTrue( map instanceof AbstractMap ); assertFalse( map instanceof List ); map = null; assertFalse( map instanceof Map );

1. Syntax of instanceof Operator

The instanceof operator tests variables to the specified type. Variable is written on the left-hand side of the operator, and type is given on the right side of the operator.

boolean value = variable instanceof ClassType; //or if(variable instanceof ClassType) < //perform some action >

2. The instanceof Operator does not need an Explicit null Check

In Java, null is a type so we do not need to check for NullPointerException when using the instanceof operator. The instanceof does it internally for us.

if(map != null && map instanceof Map) < //some action >

In the previous example, we do not need to make an explicit null check. The correct way to write the expression is:

Читайте также:  Php obj to json

3. Using instanceof with an Array

In Java, arrays are also considered objects and have associated fields and methods. So we can use instanceof operator with arrays as well.

Primitive arrays are instances of Object and self-type. e.g. int[] is type of Object and int[]. Both comparisons return true.

int[] intArr = new int[0]; Assertions.assertTrue(intArr instanceof Object); Assertions.assertTrue(intArr instanceof int[]);

Object arrays are types of Object, Object[], classtype array, and parent class type array. e.g. Integer[] is type of Object, Object[], Integer[] and Number[] ( Integer extends Number ).

Integer[] integerArr = new Integer[0]; Assertions.assertTrue(integerArr instanceof Object); Assertions.assertTrue(integerArr instanceof Object[]); Assertions.assertTrue(integerArr instanceof Integer[]); Assertions.assertTrue(integerArr instanceof Number[]);

A real-life example of using instanceof operator can be typecasting a variable to another type. The instanceof operator helps in avoiding ClassCastException in runtime.

Consider the following example where we are trying to typecast a list to LinkedList class, where the original variable is of type ArrayList. It will throw ClassCastException.

List list = new ArrayList<>(); LinkedList linkedList = (LinkedList) list; //ClassCastException

To correctly cast the variable, we can use instanceof operator. It will not result in ClassCastException.

List list = new ArrayList<>(); if(list instanceof LinkedList) < LinkedListlinkedList = (LinkedList) list; //other actions > else if(list instanceof ArrayList) < ArrayListarrayList = (ArrayList) list; //other actions >

Since Java 14, instanceof operator supports pattern matching. We can rewrite the above expression more concisely:

List list = new ArrayList<>(); if(list instanceof LinkedList linkedList) < //use linkedlist variable here >else if(list instanceof ArrayList arrayList) < //use arraylist variable here >

Drop me your questions related to the instanceof operator used for type comparison.

Источник

How to Check Object Type in Java

You can check object type in Java by using the instanceof keyword. Determining object type is important if you’re processing a collection such as an array that contains more than one type of object. For example, you might have an array with string and integer representations of numbers. You would need to determine the object type in order to store a given array item as an int data type. To learn how to check object type, follow these four steps.

  1. Open your text editor and type in the following Java statements:Java Source for Check Object Type ClassThe program creates an array of type Object and stores even numbers as strings and odd numbers as integers (using the Integer wrapper class). The program then processes the array one item at a time in order to store each item as an int data type. The instanceof operator is used to determine if the array item is an Integer or a String . For strings, you must first narrow the Object to string (see line 8 in the source code) and then use the parseInt method of the Integer class (line 9). For integers, a narrowing must be performed on the Object data type to store the value as an int data type (line 13).
  2. Save your file as CheckObjectType.java .
  3. Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter .Compile Source for Check Object Type Class
  4. You will now test your program. Type in the command to run the Java runtime launcher and then hit Enter . Notice that the output of the program verifies that the instanceof operator was used successfully to determine the object type of each array element and therefore permits a correct conversion of the data type to int .Run Tester for Derived Class
  1. How to Check Object Type in Java (this article)
  2. How to Create a Jar File in Java
  3. How to Compile Packages in Java
  4. How to Throw an Exception in Java
  5. How to Create an Exception Class in Java
  6. How to Use the super Keyword to Call a Base Class Constructor in Java
  7. How to Use the Comparator.comparing Method in Java 8
  8. How to Use System.in in Java
  9. How to Call an Interface Method in Java
  10. How to Add a Time Zone in the Java 8 Date/Time API
  11. How to Rethrow an Exception in Java
  12. How to Use the instanceof Operator with a Generic Class in Java
  13. How to Instantiate an Object in Java
  14. How to Filter Distinct Elements from a Collection in Java 8
  15. How to Create a Derived Class in Java
  16. How to Skip Elements with the Skip Method in Java 8
  17. How to Create a Java Bean
  18. How to Implement an Interface in Java
  19. How to Compare Two Objects with the equals Method in Java
  20. How to Set PATH from JAVA_HOME
  21. How to Prevent Race Conditions in Java 8
  22. How to Write a Block of Code in Java
  23. How to Display the Contents of a Directory in Java
  24. How to Group and Partition Collectors in Java 8
  25. How to Create a Reference to an Object in Java
  26. How to Reduce the Size of the Stream with the Limit Method in Java 8
  27. How to Write an Arithmetic Expression in Java
  28. How to Format Date and Time in the Java 8 Date/Time API
  29. How to Use Comparable and Comparator in Java
  30. How to Break a Loop in Java
  31. How to Use the this Keyword to Call Another Constructor in Java
  32. How to Write a Unit Test in Java
  33. How to Declare Variables in Java
  34. How to Override Base Class Methods with Derived Class Methods in Java
  35. How to Use Serialized Objects in Java
  36. How to Write Comments in Java
  37. How to Implement Functional Interfaces in Java 8
  38. How to Write Type Parameters with Multiple Bounds in Java
  39. How to Add Type and Repeating Annotations to Code in Java 8
  40. How to Use Basic Generics Syntax in Java
  41. How to Map Elements Using the Map Method in Java 8
  42. How to Work with Properties in Java
  43. How to Write while and do while Loops in Java
  44. How to Use the finally Block in Java
  45. How to Write for-each Loops in Java
  46. How to Create a Method in Java
  47. How to Continue a Loop in Java
  48. How to Handle Java Files with Streams
  49. How to Create an Interface Definition in Java
  50. How Default Base Class Constructors Are Used with Inheritance

Training Options

Course Catalog

Источник

Test object type in java

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Оцените статью