Skip to content

StringUtils

Dokkaltek edited this page Apr 10, 2025 · 1 revision

Blank or null

You can check if a string is blank or null using these methods, which are just convenience methods for Java 8. On java 11+ you can use the built-in methods for the same.

// This would return true
boolean isBlank = StringUtils.isBlank(" ");

// This checks for nulls and blanks
boolean isBlankOrNull = StringUtils.isBlankOrNull(" ");
boolean isBlankOrNull = StringUtils.isBlankOrNull(null);

Manipulate strings

Truncate strings

String sampleString = "This is a sample string";

// This would return "This"
StringUtils.truncate(sampleString, 4);

Concatenate strings

// This would concatenate all strings into one
// "This is java!" would be the result
StringUtils.concatenate("This", "is", "java!");

// This would concatenate all elements inside a list
List<String> stringList = List.of("This", "is", "java!");
StringUtils.concatenate(stringList);

Repeat strings

// This would repeat the given string
// String.repeat() does something similar, but only for chars
// It would result in "uxuuxuuxu"
StringUtils.repeat("uxu", 3);

Pad strings

You might need to make strings have a fixed width. For those cases you can pad them with spaces or other characters.

With spaces

String one = "1"

// This would result in "1         "
one = StringUtils.padRight(one, 10);

// This would result in "         1"
one = StringUtils.padLeft(one, 10);

With character

String one = "1"

// This would result in "1xxxxxxxxx"
one = StringUtils.padRightWithChar(one, 10, 'x');

// This would result in "xxxxxxxxx1"
one = StringUtils.padLeftWithChar(one, 10, 'x');

Switch case

Capitalize string

String tale = "once upon a time..."

// This would capitalize the first letter, resulting in "Once upon a time..."
tale = StringUtils.capitalize(tale);

// This would capitalize the first letter of all words, resulting in "Once Upon A Time..."
tale = StringUtils.capitalizeAll(tale);

Snake_case

String sample = "here goes nothing"

// This would put the string in snake_case, resulting in "here_goes_nothing"
tale = StringUtils.toSnakeCase(sample);

// This would put the string in SCREAMING_SNAKE_CASE, resulting in "HERE_GOES_NOTHING"
tale = StringUtils.toScreamingSnakeCase(sample);

Kebab-case

String sample = "here goes nothing"

// This would put the string in kebab-case, resulting in "here-goes-nothing"
tale = StringUtils.toKebabCase(sample);

// This would put the string in SCREAMING-KEBAB-CASE, resulting in "HERE-GOES-NOTHING"
tale = StringUtils.toScreamingKebabCase(sample);

PascalCase

String sample = "here goes nothing"

// This would put the string in PascalCase, resulting in "HereGoesNothing"
tale = StringUtils.toKebabCase(sample);

camelCase

String sample = "here goes nothing"

// This would put the string in camelCase, resulting in "hereGoesNothing"
tale = StringUtils.toCamelCase(sample);