Skip to main content

New feature: String.isEmpty(String x) and String.isNotEmpty(String x)

1 reply [Last post]
javajeffg
Offline
Joined: 2006-08-22

I would really like to see two static methods on String (isEmpty() and isNotEmpty()) to check if a reference is null or an empty String (.equals("")). This would help make the code more readable and reduce instances of NullPointerException.

I have seen too many StringUtil classes that have these methods. They should be in the String class itself.

For instance:

String firstName = lookupFirstName();
String lastName = lookupLastName();

String fullName;

if (String.isNotEmpty(firstName) && String.isNotEmpty(lastName) {
fullName = firstName + " " + lastName;
}
else if (String.isNotEmpty(firstName)) {
fullName = firstName;
}
else if (String.isNotEmpty(lastName)) {
fullName = lastName;
}
else {
fullName = "";
}

Please add both isEmpty() and isNotEmpty(). I know I could use !String.isEmpty(blahblah), but the ! operator doesn't read well ("it is not true that blahblah is empty vs. blahblah is not empty) and is easy to miss.

This would be different than the non-static isEmpty() method on String in 1.6 which takes no arguments.

Thanks,
Jeff

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
christiaan_se
Offline
Joined: 2006-07-13

I agree. I think in general there should be a review of utility methods and decide what should be included in the jdk: eg String utilities, IO utilities, but also extension of the Collection classes (Identity collections, bi-directional hashmap, etc). How many projects include the Apache commons libraries? In my opinion this should not be necessary, it should be part of the standard java library. This would really make the language more efficient for newcomers.

kind regards,
Christiaan