43

Working in c# i've found very useful two static methods of the String class :

i can't find a valid surrogate in Java, is there something similar ?

Actually i have translated the two methods in this way :

public static boolean isNullOrEmpty(String a) { return a == null || a.isEmpty(); } public static boolean isNullOrWhiteSpace(String a) { return a == null || (a.length() > 0 && a.trim().length() <= 0); } 

Is this the best way to translate these methods in Java ? What is the best way to translate these two methods in Java ?

2
  • 1
    This might be the answer for you: stackoverflow.com/q/2272169/681807 Commented Dec 12, 2011 at 15:26
  • 5
    Your second implementation is not exactly the same. An empty string will return false whereas the C# one returns true. You could remove the a.length() > 0 && and it would be the same. Commented Dec 12, 2011 at 15:29

10 Answers 10

26

I would prefer not to use String.trim to check for existence of whitespace. It is doing more work than you need, since it checks both ends of the string (even if non-whitespace was found at the other end) AND it returns a new String object. So I would prefer to implement a method to check for whitespace only.

So my suggestion (if implementing yourself) would be as follows:

public static boolean isNullOrEmpty(String s) { return s == null || s.length() == 0; } public static boolean isNullOrWhitespace(String s) { return s == null || isWhitespace(s); } private static boolean isWhitespace(String s) { int length = s.length(); if (length > 0) { for (int i = 0; i < length; i++) { if (!Character.isWhitespace(s.charAt(i))) { return false; } } return true; } return false; } 

Or taking a cue from String.trim's implementation, you could use character comparison rather than Character.isWhitespace():

// checking for whitespace like String.trim() does private static boolean isWhitespace(String s) { int length = s.length(); if (length > 0) { for (int i = 0; i < length; i++) { if (s.charAt(i) > ' ') { return false; } } return true; } return false; } 

Finally, I'd consider checking both ends of the string in each iteration, stepping inwards. This would minimize the number of iterations needed to get the answer, regardless of whether whitespace exists at the front or the end of the string.

private static boolean isWhitespace(String s) { int length = s.length(); if (length > 0) { for (int start = 0, middle = length / 2, end = length - 1; start <= middle; start++, end--) { if (s.charAt(start) > ' ' || s.charAt(end) > ' ') { return false; } } return true; } return false; } 
Sign up to request clarification or add additional context in comments.

4 Comments

Your implementation if IsNullOrWhitespace will return false if the string is empty, which doesn't match c#'s implementation. Here's an implementation that does: gist.github.com/jamiegs/5391961
Jamiegs is right. Because your are using an IsWhiteSpace method, and you could argue that "" is not whitespace but empty, then you could add a check for empty string. public static boolean isNullOrWhitespace(String s) { return s == null || s == "" || isWhitespace(s); }
Personally, I believe the only reason to use this implementation and not what the OP suggested, is the fact that "trim" uses, as it seems, a less accurate method of detecting a whitespace. Otherwise, this answer is over-engineering. I would prefer to have a cleaner code than slightly more efficient algorithm (really - just slightly!).
@sudocode since I didn't do benchmark, I can really comment on performance, but from the looks of it, both algorithms are O(n). So not sure there's any optimization. But I totally agree that if the OP is developing a library, it makes sense to optimize wherever possible.
14

You can always see c#'s implementation through .net reflector or other decompiler:

public static bool IsNullOrEmpty(string value) { if (value != null) return value.Length == 0; else return true; } 

and

public static bool IsNullOrWhiteSpace(string value) { if (value == null) return true; for (int index = 0; index < value.Length; ++index) { if (!char.IsWhiteSpace(value[index])) return false; } return true; } 

Comments

10

you can try like this

import org.apache.commons.lang.StringUtils; public class CheckEmptyStringExample { public static void main(String[] args) { String string1 = ""; String string2 = "\t\r\n"; String string3 = " "; String string4 = null; String string5 = "Hi"; System.out.println("\nString one is empty? " + StringUtils.isBlank(string1)); System.out.println("String one is not empty? " + StringUtils.isNotBlank(string1)); System.out.println("\nString two is empty? " + StringUtils.isBlank(string2)); System.out.println("String two is not empty?" + StringUtils.isNotBlank(string2)); System.out.println("\nString three is empty?" + StringUtils.isBlank(string3)); System.out.println("String three is not empty?" + StringUtils.isNotBlank(string3)); System.out.println("\nString four is empty?" + StringUtils.isBlank(string4)); System.out.println("String four is not empty?" + StringUtils.isNotBlank(string4)); System.out.println("\nString five is empty?" + StringUtils.isBlank(string5)); System.out.println("String five is not empty?" + StringUtils.isNotBlank(string5)); } } 

Comments

7

Have a look at the StringUtils class in apache commons lang.

Comments

5

In JDK11 the String class has an isBlank method which:

Returns true if the string is empty or contains only white space codepoints, otherwise false.

Although it doesn't check for nullity it's certainly closer to C#'s string.IsNullOrWhiteSpace.

You could now do:

var isNullOrWhiteSpace = str == null || str.isBlank(); 

or create a helper method:

public static boolean isNullOrWhitespace(String s) { return s == null || str.isBlank(); } 

1 Comment

This should be the accepted answer for all modern Java code. It not only feels familiar to users migrating from C# but also has less surface area for potential errors!
4

If you import com.google.common.base.Strings, you have Strings.isNullOrEmpty()

isNullOrEmpty(@Nullable String string) 

1 Comment

This doesn't answer the OP's question because it doesn't satisfy the "isNullOrWhitespace" requirement.
3

apache.commons.lang.StringUtils is the answer.

isBlank()

isEmpty()

1 Comment

And what method in StringUtils? This isn't a very helpful answer.
1

Apache Commons Lang has a vary handy set of utilities for strings: http://commons.apache.org/lang/api-release/org/apache/commons/lang3/StringUtils.html

Of course your implementation can suffice if you don't want to bother with dependencies.

Comments

0

This should be much simpler and easy to understand.

public static boolean isNullOrEmpty(String s) { return s == null || s.length() == 0; } public static boolean isNullOrWhitespace(String s) { return isNullOrEmpty(s) ? true : isNullOrEmpty(s.trim()); } 

Comments

-1

for isnullorempty: return a == null || a.length == 0;
for isnullorwhitespace you have to check every single character until you find a non whitespace one (ascii or unicode)

1 Comment

too concise and not helpful

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.