logo

Como verificar nulo em Java?

Em Java, nulo é um literal. É usado principalmente para atribuir um valor nulo a uma variável. Um valor nulo é possível para uma string, objeto ou data e hora, etc. Não podemos atribuir um valor nulo aos tipos de dados primitivos, como int, float, etc.

Na programação, geralmente precisamos verificar se um objeto ou string é nulo ou não para realizar alguma tarefa nele. Para verificar uma string nula, temos alguns métodos predefinidos de string. Vejamos alguns exemplos de diferentes tipos de dados para entender como podemos verificar se eles são nulos ou não.

Corda

Em Java, String pode ser nulo, vazio ou em branco, e cada um deles é distinto.

alinhar imagem com css

1. Uma string vazia é um objeto string que possui algum valor, mas seu comprimento é igual a zero. Por exemplo:

 String str1 = '' 

2. Uma string em branco é uma string que tem um espaço em branco como valor. Seu comprimento é sempre maior que 0 e não é vazio nem nulo. Por exemplo:

 String str2 = '' 

3. Uma string nula não tem valor e torna uma string nula atribuindo um nulo palavra-chave como um valor para ela. Por exemplo:

 String str3 = null 

Para verificar se uma String é nula ou não, usamos o operador de comparação (==). Vamos dar um exemplo para entender como podemos usá-lo para verificação de nulos.

NullCheckExample1.java

 // import required classes and packages packagejavaTpoint.javacodes; // create class NullCheckExample1 class to check whether a string is empty or null class NullCheckExample1 { // main() method start public static void main(String[] args) { // create null, empty, and blank strings String string1 = null; String string2 = ''; String string3 = ' '; String string4 = 'Test'; // check whether string1 is null, empty, or blank System.out.println('string1 is ' + checkNullEmptyBlank(string1)); // check whether string2 is null, empty, or blank System.out.println('string2 is ' + checkNullEmptyBlank(string2)); // check whether string3 is null, empty, or blank System.out.println('string3 is ' + checkNullEmptyBlank(string3)); // check whether string4 is null, empty, or blank System.out.println('string4 is ' + checkNullEmptyBlank(string4)); } // create checkNullEmptyBlank() method which check whether the string is empty, null or blank and return result to the main() method public static String checkNullEmptyBlank(String strToCheck) { // check whether the given string is null or not if (strToCheck == null) { return 'NULL'; } // check whether the given string is empty or not else if(strToCheck.isEmpty()) { return 'EMPTY'; } // check whether the given string is blank or not else if(strToCheck.isBlank()) { return 'BLANK'; } else { return 'neither NULL, EMPTY nor BLANK'; } } } 

Saída:

Como verificar nulo em Java

Objeto Data e DateTime

Date e DateTime são tipos de dados não primitivos, portanto, podem armazenar um valor nulo. Vamos dar um exemplo de objeto de data e hora para entender como podemos verificar uma data nula ou um objeto de data e hora.

fatia de matriz java

NullCheckExample2.java

 //import required classes and packages packagejavaTpoint.javacodes; importjava.text.ParseException; importjava.text.SimpleDateFormat; importjava.util.Date; importjava.util.Scanner; //create class NullCheckExample2 class to check whether the Date object is null or not public class NullCheckExample2 { // declare a variable of date type and initialize it with null public static Date d1 = null; public static Date finalResult; // main() method start public static void main(String args[]) { // declare a variable of type string that will store the user-entered date in string format String d2; // create scanner class object Scanner sc = new Scanner(System.in); System.out.print('Enter Date in dd/mm/yyyy format:'); // take input from user and initialize variable d2 = sc.nextLine(); // close scanner class obj sc.close(); // create an instance of the SimpleDateFormat class for modifying the date object SimpleDateFormatobj = new SimpleDateFormat('dd/MM/yyyy'); // use try-catch to parse string to date try { finalResult = obj.parse(d2); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } // check whether date1 and date2 is null or not by using comparison operator if(d1 == null) { System.out.println('Date d1 is NULL.'); } if(finalResult == null) { System.out.println('Date d2 is NULL.'); }else { System.out.println('Date d2 is not NULL.'); } } } 

Saída:

Como verificar nulo em Java

Objeto Java

Para verificar se um objeto Java é Nulo ou não, podemos usar o método isNull() do Objetos classe ou operador de comparação. Vamos dar um exemplo para entender como podemos usar o método isNull() ou operador de comparação para verificação nula do objeto Java.

NullCheckExample3.java

 // import required classes and packages packagejavaTpoint.javacodes; // create NullCheckExample3 class to check whether Java object is null or not public class NullCheckExample3 { // main() method start public static void main(String[] args) { // create instance of User2 User2 userObj = new User2(); // get data of User2 by calling User1 firstUser = userObj.getFirstUser(); // check whether firstUser is null or not if (firstUser == null) { System.out.println('Object is Null'); } else { System.out.println('Object is not Null'); // set name for user1 firstUser.setName('Paul'); System.out.println(firstUser.getName()); } } } // create User1 class having a name attribute class User1 { // declare name variable String name; // getter for getting name of User1 public String getName() { // return name of User1 return name; } // setter for setting name of User1 public void setName(String name) { this.name = name; } } // create class User2 having variable of type User1 class User2 { User1 obj; // getter to get object of User1 public User1 getFirstUser() { returnobj; } } 

Saída:

conectando ao banco de dados em java
Como verificar nulo em Java

NullCheckExample4.java

 // import required classes and packages packagejavaTpoint.javacodes; importjava.util.Objects; // create NullCheckExample3 class to check whether Java object is null or not public class NullCheckExample4 { // main() method start public static void main(String[] args) { // create instance of User2 User2 userObj = new User2(); // get data of User2 by calling User1 firstUser = userObj.getFirstUser(); // check whether firstUser is null or not if (Objects.isNull(firstUser) ){ System.out.println('Object is Null'); } else { System.out.println('Object is not Null'); // set name for user1 firstUser.setName('Paul'); System.out.println(firstUser.getName()); } } } // create User1 class having a name attribute class User1 { // declare name variable String name; // getter for getting name of User1 public String getName() { // return name of User1 return name; } // setter for setting name of User1 public void setName(String name) { this.name = name; } } // create class User2 having variable of type User1 class User2 { User1 obj; // getter to get object of User1 public User1 getFirstUser() { returnobj; } } 

Saída:

Como verificar nulo em Java