- A Java “instanceof null” example
- Java instanceof null — example
- But Java is strongly typed .
- Related “Java instanceof” articles
- 9 вещей о NULL в Java
- Почему Вы должны узнать о null в Java?
- Что есть null в Java
- Java instanceof operator
- 2. Java instanceof operator
- 2.1. instanceof example in Java
- 2.2. object instanceof java
- 2.3. Java instance of null check
- 2.4. Java stream instanceof
- 3. Conclusion
- 3 thoughts on “Java instanceof operator”
A Java “instanceof null” example
You might think that when the Java instanceof operator is used to test a null reference, such as a null reference to a String , instanceof would realize that even though the reference is currently null , it is a reference to a String , so you might expect instanceof to return true . but it doesn’t.
Java instanceof null — example
To demonstrate this, I created an example Java class to show this instanceof null behavior:
/** * An instanceof example, showing what "instanceof null" returns. * By Alvin Alexander, http://alvinalexander.com */ public class JavaInstanceofNullExample < public static void main(String[] a) < // create a null string String myReference = null; // use instanceof to see if myReference is of the type String if (myReference instanceof String) < // this line is not printed System.out.println("myReference is a String"); >else < // this line is printed because "instanceof null" returns false System.out.println("instanceof returned false"); >> >
As the comments show, this example class will print the following output:
instanceof returned false
But Java is strongly typed .
I’m not a big fan of this behavior when dealing with a null reference. Because Java is a strongly-typed language — and that’s one of its strengths — even though myReference is currently null, it had to initially be declared to have some type, and in this simple example we know that it was declared to be of type String — and that can’t change — so in my world view, instanceof should return true , even when the reference is null .
Anyway . in case you were wondering, that’s the way it works.
Related “Java instanceof” articles
I ran across this while working on some other Java instanceof tutorials, which you can find at these links:
9 вещей о NULL в Java
Java и null неразрывно связаны. Едва ли существует Java-программист, не встречавшийся с «null pointer exception» и это печальный факт. Даже изобретатель концепции «null» назвал ее своей ошибкой на миллиард долларов, тогда зачем Java поддерживает ее? null был здесь долгое время, и я полагаю, создатели Java знают, что он создает больше проблем чем решает, так почему же они все еще мирятся с этим. И это удивляет меня еще больше, потому что философией Java было упростить вещи, вот почему они больше не возятся с указателями, перегрузкой операторов и множественным наследованием, но почему null?Ну, я действительно не знаю ответ на этот вопрос, но, что я точно знаю, не имеет значения сколько бы null критиковался Java-программистами и open-source сообществом, мы должны жить с ним. Вместо того чтобы сожалеть, лучше узнать больше и быть уверенным что мы используем null правильно.
Почему Вы должны узнать о null в Java?
Потому что, если Вы не обратите внимания на null, будьте уверены, Java заставит страдать от ужасного java.lang.NullPointerException и Вы выучите этот урок, но пойдете более трудным путем. Написание устойчивого к «падениям» кода — это искусство и Ваша команда, заказчики и пользователи оценят это. По моему опыту, одна из основных причин NullPointerException это недостаток знаний о null в Java. Многие из Вас уже знакомы с null, остальные смогу узнать некоторые старые и новые вещи о ключевом слове null. Давайте повторим или узнаем некоторые важные вещи о null в Java.
Что есть null в Java
- Перво-наперво, null это ключевое слово в Java, так же как public , static или final . Регистр учитывается, Вы не можете писать null как Null или NULL, компилятор не распознает его и будет выброшена ошибка.
Object obj = NULL; // Not Ok Object obj1 = null //Ok
private static Object myObj; public static void main(String args[]) < System.out.println("What is value of myObjc : " + myObj); >What is value of myObjc : null
String str = null; // null can be assigned to String Integer itr = null; // you can assign null to Integer also Double dbl = null; // null can also be assigned to Double String myStr = (String) null; // null can be type cast to String Integer myItr = (Integer) null; // it can also be type casted to Integer Double myDbl = (Double) null; // yes it's possible, no error
int i = null; // type mismatch : cannot convert from null to int short s = null; // type mismatch : cannot convert from null to short byte b = null: // type mismatch : cannot convert from null to byte double d = null; //type mismatch : cannot convert from null to double Integer itr = null; // this is ok int j = itr; // this is also ok, but NullPointerException at runtime
Integer iAmNull = null; int i = iAmNull; // Remember - No Compilation Error
Exception in thread "main" java.lang.NullPointerException
Это часто происходит при работе с HashMap и Integer key . Выполнение кода, показанного ниже прервется, как только Вы его запустите.
import java.util.HashMap; import java.util.Map; /** * An example of Autoboxing and NullPointerExcpetion * * @author WINDOWS 8 */ public class Test < public static void main(String args[]) throws InterruptedException < Map numberAndCount = new HashMap<>(); int[] numbers = ; for(int i : numbers) < int count = numberAndCount.get(i); numberAndCount.put(i, count++); // NullPointerException here >> >
Output: Exception in thread "main" java.lang.NullPointerException at Test.main(Test.java:25)
Integer iAmNull = null; if(iAmNull instanceof Integer)< System.out.println("iAmNull is instance of Integer"); >else
Output : iAmNull is NOT an instance of Integer
public class Testing < public static void main(String args[])< Testing myObject = null; myObject.iAmStaticMethod(); myObject.iAmNonStaticMethod(); >private static void iAmStaticMethod() < System.out.println("I am static method, can be called by null reference"); >private void iAmNonStaticMethod() < System.out.println("I am NON static method, don't date to call me by null"); >>
Output: I am static method, can be called by null reference Exception in thread "main" java.lang.NullPointerException at Testing.main(Testing.java:11)
public void print(Object obj)
public class Test < public static void main(String args[]) throws InterruptedException < String abc = null; String cde = null; if(abc == cde)< System.out.println("null == null is true in Java"); >if(null != null) < System.out.println("null != null is false in Java"); >// classical null check if(abc == null) < // do something >// not ok, compile time error if(abc > null) < >> >
Output: null == null is true in Java
Java instanceof operator
In this article, we will discuss the Java instanceof operator with examples.
2. Java instanceof operator
The Java instanceof operator (type comparison) compares an object to a specified type. So you can use it to check if an object is an instance of a:
The syntax of the instance of operator is:
The return type of the instance of is a boolean value: true or false.
The instance of is based on is-a relationship, meaning it depends on Inheritance, which can be of two types Class Inheritance or Interface Inheritance. Thus, you can say “A target object is a type of its own class / inheritance class (superclass) / interface”
Also, it is unidirectional. For example, House is a Building. But Building is not a House.
2.1. instanceof example in Java
Let’s take an instanceof example to understand.
Consider the below code that contains interface Vehicle . The classes Bike and Car implements the Vehicle interface.
interface Vehicle <> class Bike implements Vehicle < final int numberOfWheels = 2; >class Car implements Vehicle
The below getWheelCount method takes the object vehicle of type Vehicle . We use instanceof to check whether the vehicle instance is of type Car or Bike .
Since instanceof returns true or false as result, we can use it with if-else statement.
public static int getWheelCount(Vehicle vehicle) throws IllegalArgumentException < if (vehicle instanceof Car) < Car car = (Car) vehicle; return car.wheelCount; >else if (vehicle instanceof Bike) < Bike bike = (Bike) vehicle; return bike.numberOfWheels; >else < throw new IllegalArgumentException("Unrecognized vehicle"); >>
After checking the instance type of the object, we are casting it to the corresponding type for accessing its methods and variables.
Let’s take another example that includes both superclass and interface.
For example, the obj1 is a direct object of Vehicle and is a type of only Vehicle . However, obj2 is a type of Car , Vehicle and also Machine .
class InstanceofDemo < public static void main(String[] args) < Vehicle obj1 = new Vehicle(); Car obj2 = new Car(); System.out.println("obj1 instanceof Vehicle: " + (obj1 instanceof Vehicle)); /* true */ System.out.println("obj1 instanceof Car: " + (obj1 instanceof Car)); /* false */ System.out.println("obj1 instanceof Machine: " + (obj1 instanceof Machine)); /* false */ System.out.println("obj2 instanceof Machine: " + (obj2 instanceof Machine)); /* true */ System.out.println("obj2 instanceof Car: " + (obj2 instanceof Car)); /* true */ System.out.println("obj2 instanceof Machine: " + (obj2 instanceof Machine)); /* true */ >> class Vehicle <> class Car extends Vehicle implements Machine <> interface Machine <>
2.2. object instanceof java
Class Object is the root of the class hierarchy. Every class has Object as a superclass. So when you compare any instance with Object class, it would always evaluate to true.
Car car = new Car(); System.out.println(car instanceof Object); /* prints true */
2.3. Java instance of null check
You can compare a null instance against a type using the instanceof operator. So, there is no need to perform null check before calling the instanceof operator.
For example, the below car variable is null , so comparing it against the type Object returns false.
Car car = null; System.out.println(car instanceof Object); /* prints false */
2.4. Java stream instanceof
You can use instanceof with stream filter. In the below example, we are filtering all the car objects from the vehicleList as below:
vehicleList.stream() .filter(vehicle -> vehicle instanceof Car) .map (vehicle -> (Car) vehicle) .collect(Collectors.toList());
3. Conclusion
To sum up, this article focuses on Java instanceof and its use cases. See this article on instanceof pattern matching introduced in Java 14 as a preview feature and available in Java 16 (JEP 394) as production.