Search code examples
javastringjava-8charnull-character

How best to determine if a String contains only null characters?


What's the right way to check if a string contains null characters only?

String s = "\u0000";
if(s.charAt(0) == 0) {
   System.out.println("null characters only");
}

Or

String s = "\0\0";
for(int i = 0; i < s.length(); i++) {
   if(s.charAt(i) == 0) 
       continue;

   else break;

}

Both work. But is there a better and more concise way to perform this check. Is there a utility to check if a string in java contains only null characters(\u0000 OR \0) ?

And what is the difference between '\0' and '\u0000'?


Solution

  • You can use a regular expression

    to match one or more \u0000

    boolean onlyNulls = string.matches("\u0000+");  // or "\0+"
    

    use * instead of + to also match the empty string


    (the stream solution by Sweeper is my preferred solution - IMHO it better resembles the intended task, despite I would use '\u0000' instead of 0)