- Check if an Object Is Null in Java
- Java Check if Object Is Null Using the == Operator
- Java Check if Object Is Null Using java.utils.Objects
- Java: Check if String is Null, Empty or Blank
- Introduction
- Using the Length of the String
- Using the isEmpty() Method
- Using the equals() Method
- Using the StringUtils Class
- Free eBook: Git Essentials
- Java: как проверить, является ли объект null?
- 8 ответов
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.
Источник
Java: Check if String is Null, Empty or Blank
Introduction
In Java, there is a distinct difference between null , empty, and blank Strings.
- An empty string is a String object with an assigned value, but its length is equal to zero.
- A null string has no value at all.
- A blank String contains only whitespaces, are is neither empty nor null , since it does have an assigned value, and isn’t of 0 length.
In this tutorial, we’ll look at how to check if a String is Null, Empty or Blank in Java.
Using the Length of the String
As mentioned before, a string is empty if its length is equal to zero. We will be using the length() method, which returns the total number of characters in our string.
The code above will produce the following output:
The String is blank, so it’s obviously neither null nor empty. Now, based just on the length, we can’t really differentiate between Strings that only contain whitespaces or any other character, since a whitespace is a Character .
Note: It’s important to do the null -check first, since the short-circuit OR operator || will break immediately on the first true condition. If the string, in fact, is null , all other conditions before it will throw a NullPointerException .
Using the isEmpty() Method
The isEmpty() method returns true or false depending on whether or not our string contains any text. It’s easily chainable with a string == null check, and can even differentiate between blank and empty strings:
The trim() method removes all whitespaces to the left and right of a String, and returns the new sequence. If the String is blank, after removing all whitespaces, it’ll be empty, so isEmpty() will return true .
Running this piece of code will give us the following output:
Using the equals() Method
The equals() method compares the two given strings based on their content and returns true if they’re equal or false if they are not:
In much the same fashion as the before, if the trimmed string is «» , it was either empty from the get-go, or was a blank string with 0..n whitespaces:
Using the StringUtils Class
The Apache Commons is a popular Java library that provides further functionality. StringUtils is one of the classes that Apache Commons offers. This class contains methods used to work with Strings , similar to the java.lang.String .
If you’re unfamiliar with Apache Commons’ helper classes, we strongly suggest reading our Guide to the StringUtils class.
Since we’ll be using Apache Commons for this approach, let’s add it as a dependency:
Or, if you’re using Gradle:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
Источник
Java: как проверить, является ли объект null?
Я создаю приложение, которое извлекает изображения из интернета. Если изображение не может быть извлечено, следует использовать другое локальное изображение.
при попытке выполнить следующие строки:
линия if (drawable.equals (null)) создает исключение, если drawable равно null.
кто-нибудь знает, как следует проверять значение drawable, чтобы не создавать исключение в случае, если оно равно null и извлекать локальный образ (execute drawable = getRandomDrawable ())?
8 ответов
Отредактированное Решение Java 8:
можно объявить drawable final в этом случае.
как отметил Chasmo, Android не поддерживает Java 8 на данный момент. Поэтому такое решение возможно только в других контекстах.
на equals() проверяет метод стоимостью равенство, что означает, что он сравнивает содержание двух объектов. С null не является объектом, это сбой при попытке сравнить содержимое вашего объекта с содержимым null .
на == проверка оператора ссылка равенство, что означает, что он выглядит, являются ли два объекта на самом деле тот же самый объект. Это не требует объекты, которые действительно существуют; два несуществующих объекта ( null ссылки) также равны.
я использую такой подход:
таким образом, я нахожу, улучшает читаемость строки — поскольку я быстро читаю исходный файл, я вижу, что это нулевая проверка.
Что касается того, почему вы не можете позвонить .equals() на объекте, который может быть null , Если ссылка на объект, у вас есть (а именно ‘мешочки’) и в самом деле null , оно не указывает на объект в куче. Это означает, что в куче нет объекта, на котором вызов equals() can преуспевать.
if (yourObject instanceof yourClassName) будет оценено как false если yourObject и null .
В приведенной выше строке вызывается » equals(. )» метод объекта мешочки.
Итак, когда drawable не null и это реальный объект, то все идет хорошо, так как вызов метода» equals(null) «вернет»false»
но когда «drawable» равно null, это означает вызов » equals(. ) «метод на нулевом объекте означает вызов метода на объекте, который не существует, поэтому он вызывает «NullPointerException»
чтобы проверить, существует ли объект, и это не null, используйте следующий
В приведенном выше условии мы проверяем, что ссылочная переменная «drawable» равна null или содержит некоторое значение (ссылка на ее объект), поэтому она не будет выдавать исключение в случае, если drawable равно null как проверка
вероятно, немного эффективнее поймать исключение NullPointerException. Вышеуказанные методы означают, что среда выполнения проверяет наличие нулевых указателей дважды.
использовать компания Google гуава библиотеки для обработки is-null-check (обновление deamon)
Источник