How best to determine if a String contains only null characters?
5
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'
?
java string java-8 char null-character
-
4Hmm. I am hard-pressed to think of a valid use-case that involves testing to see if a string contains just NUL characters. (The only use-cases I can think of involve treating non-text data as text ... and that's conceptually wrong.) – Stephen C May 13 at 3:27
-
@StephenC, my service needs to call a downstream server, which is returning a parameter in json body say "eCode", based on this I need to check if there's something went wrong in downstream server, so if this string is empty OR contains only null characters than everything is fine, other wise if "eCode" contains anything else than I need to returned an error response to the upstreams. – tusharRawat May 13 at 18:37
-
1OK ... so why is a server sending you a string that contains NUL characters in a JSON response? That is ... umm ... bad design. Are you sure that you haven't misunderstood the spec? (Might it actually say "an empty string or null"? There is a null value in JSON.) – Stephen C May 14 at 5:30
-
No I have even tested calling the service, they are returning null character string, I initially thought it should be null or "" empty string but as my test cases got failed than I realized that they are returning something else, and that's indeed a bad design, I concur, But you know, I have to deal with it as I don't have the ownership of other service. – tusharRawat May 14 at 12:46
Add a comment
|