Skip to content

Commit

Permalink
Add Strings.isNullOfEmpty(String) and Strings.emptyToNull(String), re #…
Browse files Browse the repository at this point in the history
  • Loading branch information
safris committed May 21, 2024
1 parent ed14eb7 commit aa7fbaa
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/main/java/org/libj/lang/Strings.java
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,26 @@ private static String getRandom(final SecureRandom secureRandom, final int lengt
return new String(array);
}

/**
* Returns {@code true} if the given string is null or its length is {@code 0}, otherwise {@code false}.
*
* @param string The string to check.
* @return {@code true} if the string is null or its length is {@code 0}, otherwise {@code false}.
*/
public static boolean isNullOrEmpty(final String string) {
return string == null || string.length() == 0;
}

/**
* Returns the given string if it is nonempty; otherwise {@code null}.
*
* @param string The string to test.
* @return The given string if it is nonempty; otherwise {@code null}.
*/
public static String emptyToNull(final String string) {
return string == null || string.length() == 0 ? null : string;
}

/**
* Returns a randomly constructed alphanumeric string of the specified length.
*
Expand Down
14 changes: 14 additions & 0 deletions src/test/java/org/libj/lang/StringsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,20 @@ public class StringsTest {

private static final Random r = new Random();

@Test
public void testIsNullOrEmpty() {
assertTrue(Strings.isNullOrEmpty(null));
assertTrue(Strings.isNullOrEmpty(""));
assertFalse(Strings.isNullOrEmpty(" "));
}

@Test
public void testEmptyToNull() {
assertNull(null);
assertNull(Strings.emptyToNull(""));
assertNotNull(Strings.emptyToNull(" "));
}

@Test
public void testIndexOf1() {
for (int i = 0; i < 10000; ++i) { // [N]
Expand Down

0 comments on commit aa7fbaa

Please sign in to comment.