Java operator "instanceof" - Instructions and examples
In this practical tip, we will explain how you can use the instanceof operator in Java with pinpoint accuracy.
Java operator "instanceof" - Instructions and examples
Use the instanceof operator to check whether a particular object is an instance of a special class. You normally use this operator if you have a parameter or an object from an interface or a super class and you want to check whether the actual object has other types. The following code checks, for example, which parameter it is.
- public void doSomething (Number parameter1) {
- if (parameter1 instanceof Double) {
- System.out.println ("The parameter is a double!");
- } else if (parameter1 instanceof integer) {
- System.out.println ("The parameter is an integer!"); }
- if (parameter1 instanceof Comparable) {
- System.out.println ("The parameter occurs in the Comparable Interface!"); }}
In the next practical tip, we will give you a basic introduction to the Java programming language.