Checking for a not null, not blank String in Java

前端 未结 8 1651
猫巷女王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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-31 14:13

    Why can't you simply use a nested ternary operator to achieve this.Please look into the sample code public static void main(String[] args) { String s = null; String s1=""; String s2="hello"; System.out.println(" 1 "+check(s)); System.out.println(" 2 "+check(s1)); System.out.println(" 3 "+check(s2)); } public static boolean check(String data) { return (data==null?false:(data.isEmpty()?false:true)); }

    and the output is as follows

    1 false 2 false 3 true

    here the 1st 2 scenarios returns false (i.e null and empty)and the 3rd scenario returns true

提交回复
热议问题