Java Check if a String is empty or null
By:Roy.LiuLast updated:2019-08-11
In Java, we can use (str != null && !str.isEmpty()) to make sure the String is not empty or null.
StringNotEmpty.java
package com.mkyong; public class StringNotEmpty { public static void main(String[] args) { System.out.println(notEmpty("")); // false System.out.println(notEmpty(null)); // false System.out.println(notEmpty("hello")); // true System.out.println(notEmpty(" ")); // true, a space... private static boolean notEmpty(String str) { if (str != null && !str.isEmpty()) { return true; } else { return false;
Output
false false true true
If we want empty space like notEmpty(" ") to return false, update the code with .trim(),
private static boolean notEmpty(String str) { if (str != null && !str.trim().isEmpty()) { return true; } else { return false;
From:一号门
COMMENTS