logo

Come controllare null in Java?

A Giava, nullo è un valore letterale. Viene utilizzato principalmente per assegnare un valore nullo a una variabile. Un valore nullo è possibile per una stringa, un oggetto, una data e un'ora, ecc. Non possiamo assegnare un valore nullo ai tipi di dati primitivi come int, float, ecc.

Nella programmazione, solitamente dobbiamo verificare se un oggetto o una stringa è nulla o meno per eseguire qualche operazione su di esso. Per verificare una stringa nulla, abbiamo alcuni metodi di stringa predefiniti. Prendiamo alcuni esempi di diversi tipi di dati per capire come possiamo verificare se sono nulli o meno.

Corda

In Java, String può essere null, vuoto o vuoto e ognuno di essi è distinto.

1. Una stringa vuota è un oggetto stringa avente un valore, ma la sua lunghezza è uguale a zero. Per esempio:

 String str1 = '' 

2. Una stringa vuota è una stringa che ha uno spazio bianco come valore. La sua lunghezza è sempre maggiore di 0 e non è né vuota né nulla. Per esempio:

 String str2 = '' 

3. Una stringa nulla non ha valore e rende nulla una stringa assegnando a nullo parola chiave come valore. Per esempio:

 String str3 = null 

Per verificare se una stringa è nulla o meno, utilizziamo l'operatore di confronto (==). Facciamone un esempio per capire come possiamo usarlo per il controllo nullo.

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'; } } } 

Produzione:

Come controllare null in Java

Oggetto Date e DateTime

Date e DateTime sono entrambi tipi di dati non primitivi, quindi possono memorizzare un valore null. Prendiamo un esempio di un oggetto data e ora per capire come possiamo controllare un oggetto data o datetime nullo.

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.'); } } } 

Produzione:

Come controllare null in Java

Oggetto Java

Per verificare se un oggetto Java è Null o meno, possiamo utilizzare il metodo isNull() di Oggetti operatore di classe o di confronto. Facciamo un esempio per capire come possiamo utilizzare il metodo isNull() o l'operatore di confronto per il controllo nullo dell'oggetto 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; } } 

Produzione:

Come controllare null in 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; } } 

Produzione:

Come controllare null in Java