Checking for a not null, not blank String in Java

前端 未结 8 1756
猫巷女王i
猫巷女王i 2021-01-31 13:24

I am trying to check if a Java String is not null, not empty and not whitespace.

In my mind, this code should have been quite up for the job.

         


        
8条回答
  •  南旧
    南旧 (楼主)
    2021-01-31 14:16

    This simple code will do enough:

    public static boolean isNullOrEmpty(String str) {
        return str == null || str.trim().equals("");
    }
    

    And the unit tests:

    @Test
    public void testIsNullOrEmpty() {
        assertEquals(true, AcdsUtils.isNullOrEmpty(""));
        assertEquals(true, AcdsUtils.isNullOrEmpty((String) null));
        assertEquals(false, AcdsUtils.isNullOrEmpty("lol    "));
        assertEquals(false, AcdsUtils.isNullOrEmpty("HallO"));
    }
    

提交回复
热议问题