English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In questo programma, imparerai a utilizzare le istruzioni if-else e le funzioni Java per controllare se una stringa è vuota o null.
public class Null { public static void main(String[] args) { String str1 = null; String str2 = ""; if(isNullOrEmpty(str1)) System.out.println("La prima stringa è null o vuota."); else System.out.println("La prima stringa non è null o vuota."); if(isNullOrEmpty(str2)) System.out.println("La seconda stringa è null o vuota."); else System.out.println("La seconda stringa non è null o vuota."); } public static boolean isNullOrEmpty(String str) { if(str != null && !str.isEmpty()) return false; return true; } }
Quando si esegue il programma, l'output è:
La prima stringa è null o vuota. La seconda stringa è null o vuota.
Nel programma sopra, abbiamo due stringhe str1 e str2. str1 contiene un valore null, str2 è una stringa vuota.
Abbiamo anche creato una funzione isNullOrEmpty(), come suggerisce il nome, che verifica se una stringa è null o vuota. Usa != null e il metodo isEmpty() della stringa per effettuare il controllo.
In altre parole, se una stringa non è null e isEmpty() restituisce false, allora non è né null né vuota. Altrimenti, sì.
Ma se la stringa contiene solo caratteri di spazio (spazi), il programma sopra non restituirà empty. Tecnicamente, isEmpty() trova che contiene spazi e restituisce false. Per le stringhe con spazi, usiamo il metodo trim() della stringa per rimuovere tutti i caratteri di spazio iniziali e finali.
public class Null { public static void main(String[] args) { String str1 = null; String str2 = "\t\t\t\t"; if(isNullOrEmpty(str1)) System.out.println("str1 è null o vuoto."); else System.out.println("str1 non è null o vuota."); if(isNullOrEmpty(str2)) System.out.println("str2 è null o vuota."); else System.out.println("str2 non è null o vuota."); } public static boolean isNullOrEmpty(String str) { if(str != null && !str.trim().isEmpty()) return false; return true; } }
Quando si esegue il programma, l'output è:
str1 è null o vuota. str2 è null o vuota.
In isNullorEmpty(), abbiamo aggiunto un metodo extra trim(), che può rimuovere tutti gli spazi iniziali e finali dalla stringa fornita.
Quindi, ora, se la stringa contiene solo spazi, la funzione restituirà true.