Check if an Object Is Null in Java
This tutorial will go through the methods to check if an object is null in Java with some briefly explained examples.
Java Check if Object Is Null Using the == Operator
As an example, we have created two classes — User1 and User2 . The class User1 has one instance variable name and the Getter and Setter methods to update and retrieve the instance variable name . The User2 class has one method, getUser1Object , which returns the instance of class User1 .
In the main method, we create an object of the User2 class named user and call the getUser1Object() on it, which returns the instance of the class User1 . Now we check if the instance of the User1 class returned by the method is null or not by using the == operator in the if-else condition.
If the object returned is not null , we can set the name in the User1 class by calling the setter method of the class and passing a custom string as a parameter to it.
Java Check if Object Is Null Using java.utils.Objects
The java.utils.Objects class has static utility methods for operating an object. One of the methods is isNull() , which returns a boolean value if the provided reference is null, otherwise it returns false.
We have created two classes — User1 and User2 as shown in the code below. In the main method, we created an object of the User2 class using the new keyword and called the getUser1Object() method. It returns an object of class User1 , which we later store in getUser1Object .
To check if it is null, we call the isNull() method and pass the object getUserObject as a parameter. It returns true as the passed object is null.
Как общаться с null в Java и не страдать
Java и null неразрывно связаны. Трудно найти Java-программиста, который не сталкивался с NullPointerException . Если даже автор понятия нулевого указателя признал его «ошибкой на миллиард долларов», почему он сохранился в Java? null присутствует в Java уже давно, и я уверен, что разработчики языка знают, что он создает больше проблем, чем решает. Это удивительно, ведь философия Java — делать вещи как можно более простыми. Если разработчики отказались от указателей, перегрузки операторов и множественного наследования, то почему они оставили null ? Я не знаю ответа на этот вопрос. Однако не имеет значения, насколько много критики идет в адрес null в Java, нам придется с этим смириться. Вместо того, чтобы жаловаться, давайте лучше научимся правильно его использовать. Если быть недостаточно внимательным при использовании null , Java заставит вас страдать с помощью ужасного java.lang.NullPointerException . Наиболее частая причина NullPointerException — недостаточное понимание тонкостей использования null . Давайте вспомним самые важные вещи о нем в Java.
Что такое null в Java
Как мы уже выяснили, null очень важен в Java. Изначально он служил, чтобы обозначить отсутствие чего-либо, например, пользователя, ресурса и т. п. Но уже через год выяснилось, что он приносит много проблем. В этой статье мы рассмотрим основные вещи, которые следует знать о нулевом указателе в Java, чтобы свести к минимуму проверки на null и избежать неприятных NullPointerException .
1. В первую очередь, null — это ключевое слово в Java, как public , static или final . Оно регистрозависимо, поэтому вы не сможете написать Null или NULL , компилятор этого не поймет и выдаст ошибку:
Эта проблема часто возникает у программистов, которые переходят на Java с других языков, но с современными средами разработки это несущественно. Такие IDE, как Eclipse или Netbeans, исправляют эти ошибки, пока вы набираете код. Но во времена Блокнота, Vim или Emacs это было серьезной проблемой, которая отнимала много времени.
2. Так же, как и любой примитивный тип имеет значение по умолчанию (0 у int , false у boolean ), null — значение по умолчанию любого ссылочного типа, а значит, и для любого объекта. Если вы объявляете булеву переменную, ей присваивается значение false . Если вы объявляете ссылочную переменную, ей присваивается значение null , вне зависимости от области видимости и модификаторов доступа. Единственное, компилятор предупредит о попытке использовать неинициализированную локальную переменную. Для того, чтобы убедиться в этом, вы можете создать ссылочную переменную, не инициализируя ее, и вывести ее на экран:
Это справедливо как для статических, так и для нестатических переменных. В данном случае мы объявили myObj как статическую переменную для того, чтобы ее можно было использовать в статическом методе main .
3. Несмотря на распространенное мнение, null не является ни объектом, ни типом. Это просто специальное значение, которое может быть присвоено любому ссылочному типу. Кроме того, вы также можете привести null к любому ссылочному типу:
Как видите, приведение null к ссылочному типу не вызывает ошибки ни при компиляции, ни при запуске. Также при запуске не будет NullPointerException , несмотря на распространенное заблуждение.
4. null может быть присвоен только переменной ссылочного типа. Примитивным типам — int , double , float или boolean — значение null присвоить нельзя. Компилятор не допустит этого и выдаст ошибку:
Итак, попытка присвоения значения null примитивному типу — ошибка времени компиляции, но вы можете присвоить null типу-обертке, а затем присвоить это значение соответствуему примитиву. Компилятор ругаться не будет, но при выполнении кода будет брошено NullPointerException . Это происходит из-за автоматического заворачивания (autoboxing) в Java
5. Любой объект класса-обертки со значением null кинет NullPointerException при разворачивании (unboxing). Некоторые программисты думают, что обертка автоматически присвоит примитиву значение по умолчанию (0 для int , false для boolean и т. д.), но это не так:
Если вы запустите этот код, вы увидите Exception in thread «main» java.lang.NullPointerException в консоли. Это часто случается при работе с HashMap с ключами типа Integer . Код ниже сломается, как только вы его запустите:
Этот код выглядит простым и понятным. Мы ищем, сколько каждое число встречается в массиве, это классический способ поиска дубликатов в массиве в Java. Мы берем предыдущее значение количества, инкрементируем его и кладем обратно в HashMap . Мы полагаем, что Integer позаботится о том, чтобы вернуть значение по умолчанию для int , однако если числа нет в HashMap , метод get() вернет null , а не 0. И при оборачивании выбросит NullPoinerException . Представьте, что этот код завернут в условие и недостаточно протестирован. Как только вы его запустите на продакшен – УПС!
6. Оператор instanceof вернет false , будучи примененным к переменной со значением null или к литералу null :
Это важное свойство оператора instanceof , которое делает его полезным при приведении типов.
7. Возможно, вы уже знаете, что если вызвать нестатический метод по ссылке со значением null , результатом будет NullPointerException . Но зато вы можете вызвать по ней статический метод класса:
Результат выполнения этого кода:
8. Вы можете передавать null в любой метод, который принимает ссылочный тип, например, public void print(Object obj) может быть вызван так: print(null) . С точки зрения компилятора ошибки здесь нет, но поведение такого кода целиком зависит от реализации метода. Безопасный метод не кидает NullPointerException в этом случае, а тихо завершает работу. Если бизнес-логика позволяет, лучше писать безопасные методы.
9. Вы можете сравнивать null , используя оператор == («равно») и != («не равно»), но не с арифметическими или логическими операторами (такими как «больше» или «меньше»). В отличие от SQL, в Java null == null вернет true :
Вывод этого кода:
Вот и все, что надо знать о null в Java. При наличии небольшого опыта и с помощью простых приемов вы можете сделать свой код безопасным. Поскольку null может рассматриваться как пустая или неинициализированная переменная, важно документировать поведение метода при получении null . Помните, что любая созданная и не проинициализированная переменная имеет по умолчанию значение null и что вы не можете вызвать метод объекта или обратиться к его полю, используя null .
Check if Object Is Null in Java
An object in Java is an instance of a class. It is a real entity existing in the memory opposite to the class that acts as a blueprint for the object.
The object represents data and methods for a particular entity that are defined by the class.
In this article, you will learn to check if the object contains a null reference in Java.
Comparison Operator to Check if Object Is Null in Java
The comparison operator (==) in Java is widely used to perform the comparison between two entities. The result of the comparison is boolean true if both the entities are the same, otherwise, the result is boolean false.
You can use this operator to check if an object is null in Java by comparing the object with the ‘null’ value.
The code defines a class named MyClass that has a String field name . There are two constructors to instantiate the object of the class.
The code defines two objects of the MyClass class named as myObj and myObj2 . The myObj object is not instantiated therefore it should have the null reference. The other object is instantiated making it a non-null object.
Best way to check for null values in Java?
Before calling a function of an object, I need to check if the object is null, to avoid throwing a NullPointerException .
What is the best way to go about this? I’ve considered these methods.
Which one is the best programming practice for Java?
19 Answers 19
Method 4 is best.
will use short-circuit evaluation, meaning it ends if the first condition of a logical AND is false.
The last and the best one. i.e LOGICAL AND
Because in logical &&
it is not necessary to know what the right hand side is, the result must be false
- Do not catch NullPointerException . That is a bad practice. It is better to ensure that the value is not null.
- Method #4 will work for you. It will not evaluate the second condition, because Java has short-circuiting (i.e., subsequent conditions will not be evaluated if they do not change the end-result of the boolean expression). In this case, if the first expression of a logical AND evaluates to false, subsequent expressions do not need to be evaluated.
Method 4 is far and away the best as it clearly indicates what will happen and uses the minimum of code.
Method 3 is just wrong on every level. You know the item may be null so it’s not an exceptional situation it’s something you should check for.
Method 2 is just making it more complicated than it needs to be.
Method 1 is just method 4 with an extra line of code.
In Java 7, you can use Objects.requireNonNull() . Add an import of Objects class from java.util .
As others have said #4 is the best method when not using a library method. However you should always put null on the left side of the comparison to ensure you don’t accidentally assign null to foo in case of typo. In that case the compiler will catch the mistake.
I would say method 4 is the most general idiom from the code that I’ve looked at. But this always feels a bit smelly to me. It assumes foo == null is the same as foo.bar() == false.
That doesn’t always feel right to me.
Method 4 is my preferred method. The short circuit of the && operator makes the code the most readable. Method 3, Catching NullPointerException, is frowned upon most of the time when a simple null check would suffice.
Simple one line Code to check for null :
Update
Generic Method to handle Null Values in Java
If that object is not null we are going to do the following things.
a. We can mutate the object (I)
b. We can return something(O) as output instead of mutating the object (I)
c. we can do both
In this case, We need to pass a function which needs to take the input param(I) which is our object If we take it like that, then we can mutate that object if we want. and also that function may be something (O).
If an object is null then we are going to do the following things
a. We may throw an exception in a customized way
b. We may return something.
In this case, the object is null so we need to supply the value or we may need to throw an exception.
I take two examples.
- If I want to execute trim in a String then that string should not be null. In that case, we have to additionally check the null value otherwise we will get NullPointerException
- Another function which I want to set a new value to object if that object is not null otherwise I want to throw a runtime exception.
With my Explanation, I have created a generic method that takes the value(value may be null), a function that will execute if the object is not null and another supplier function that will execute if the object is null.
GenericFunction
So after having this generic function, we can do as follow for the example methods 1.
Here, the nonNullExecutor Function is trim the value (Method Reference is used). nullExecutorFunction is will return null since It is an identity function.