📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
I frequently use these String utility methods in my day-to-day project work and I thought I have to create an article on this so that everyone can get help from it.
Utility methods perform common, often reused functions and they don't require to have object-level state, that is they tend to be global functions.
Empty Checks Methods
1. isEmpty(CharSequence cs)
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
@Test
public void isEmptyTest() {
assertTrue(isEmpty(null));
assertTrue(isEmpty(""));
assertFalse(isEmpty(" "));
assertFalse(isEmpty("bob"));
assertFalse(isEmpty(" bob "));
}
2. isNotEmpty(final CharSequence cs)
public static boolean isNotEmpty(final CharSequence cs) {
return !isEmpty(cs);
}
public static boolean isEmpty(final CharSequence cs) {
return cs == null || cs.length() == 0;
}
3. isAnyEmpty(final CharSequence... css)
public static boolean isAnyEmpty(final CharSequence... css) {
if (css != null && css.length == 0) {
return false;
}
for (final CharSequence cs : css){
if (isEmpty(cs)) {
return true;
}
}
return false;
}
@Test
public void isAnyEmptyTest() {
assertTrue(isAnyEmpty((String) null));
assertFalse(isAnyEmpty((String[]) null));
assertTrue(isAnyEmpty(null, "foo"));
assertTrue(isAnyEmpty("", "bar"));
assertTrue(isAnyEmpty("bob", ""));
assertTrue(isAnyEmpty(" bob ", null));
assertFalse(isAnyEmpty("foo", "bar"));
assertFalse(isAnyEmpty(new String[]{}));
assertTrue(isAnyEmpty(new String[]{""}));
}
4. isBlank(final CharSequence cs)
public static boolean isBlank(final CharSequence cs) {
int strLen;
if (cs == null || (strLen = cs.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(cs.charAt(i))) {
return false;
}
}
return true;
}
@Test
public void isBlankTest() {
assertTrue(isBlank(null));
assertTrue(isBlank(""));
assertTrue(isBlank(" "));
assertFalse(isBlank("bob"));
assertFalse(isBlank(" bob "));
}
5. isNotBlank(final CharSequence cs)
public static boolean isNotBlank(final CharSequence cs) {
return !isBlank(cs);
}
6. isAnyBlank(final CharSequence... css)
public static boolean isAnyBlank(final CharSequence... css) {
if (css != null && css.length == 0) {
return false;
}
for (final CharSequence cs : css){
if (isBlank(cs)) {
return true;
}
}
return false;
}
@Test
public void isAnyBlankTest() {
assertFalse(isAnyBlank((String[]) null));
assertTrue(isAnyBlank((String) null));
assertTrue(isAnyBlank(null, "foo"));
assertTrue(isAnyBlank(null, null));
assertTrue(isAnyBlank("", "bar"));
assertTrue(isAnyBlank("bob", ""));
assertTrue(isAnyBlank(" bob ", null));
assertTrue(isAnyBlank(" ", "bar"));
assertFalse(isAnyBlank(new String[] {}));
assertTrue(isAnyBlank(new String[] { "" }));
assertFalse(isAnyBlank("foo", "bar"));
}
Check for Whitespace
7. containsWhitespace(CharSequence seq)
public static boolean containsWhitespace(final CharSequence seq) {
if (isEmpty(seq)) {
return false;
}
final int strLen = seq.length();
for (int i = 0; i < strLen; i++) {
if (Character.isWhitespace(seq.charAt(i))) {
return true;
}
}
return false;
}
@Test
public void testContainsWhitespace() {
assertFalse(containsWhitespace(null));
assertFalse(containsWhitespace(""));
assertFalse(containsWhitespace("a"));
assertFalse(containsWhitespace("abc"));
assertTrue(containsWhitespace(" "));
assertTrue(containsWhitespace(" a"));
assertTrue(containsWhitespace("abc "));
assertTrue(containsWhitespace("a b"));
assertTrue(containsWhitespace("a b"));
}
Trim Methods
8. trimArrayElements( String[] array)
/**
* Trim the elements of the given {@code String} array,
* calling {@code String.trim()} on each of them.
* @param array the original {@code String} array
* @return the resulting array (of the same size) with trimmed elements
*/
public static String[] trimArrayElements( String[] array) {
if (isEmpty(array)) {
return new String[0];
}
String[] result = new String[array.length];
for (int i = 0; i < array.length; i++) {
String element = array[i];
result[i] = (element != null ? element.trim() : null);
}
return result;
}
9. trimWhitespace(String str)
/**
* Trim leading and trailing whitespace from the given {@code String}.
* @param str the {@code String} to check
* @return the trimmed {@code String}
* @see java.lang.Character#isWhitespace
*/
public static String trimWhitespace(String str) {
if (!hasLength(str)) {
return str;
}
int beginIndex = 0;
int endIndex = str.length() - 1;
while (beginIndex <= endIndex && Character.isWhitespace(str.charAt(beginIndex))) {
beginIndex++;
}
while (endIndex > beginIndex && Character.isWhitespace(str.charAt(endIndex))) {
endIndex--;
}
return str.substring(beginIndex, endIndex + 1);
}
@Test
public void testTrimWhitespace() {
assertEquals(null, trimWhitespace(null));
assertEquals("", trimWhitespace(""));
assertEquals("", trimWhitespace(" "));
assertEquals("", trimWhitespace("\t"));
assertEquals("a", trimWhitespace(" a"));
assertEquals("a", trimWhitespace("a "));
assertEquals("a", trimWhitespace(" a "));
assertEquals("a b", trimWhitespace(" a b "));
assertEquals("a b c", trimWhitespace(" a b c "));
}
10. trimAllWhitespace(String str)
/**
* Trim <i>all</i> whitespace from the given {@code String}:
* leading, trailing, and in between characters.
* @param str the {@code String} to check
* @return the trimmed {@code String}
* @see java.lang.Character#isWhitespace
*/
public static String trimAllWhitespace(String str) {
if (!hasLength(str)) {
return str;
}
int len = str.length();
StringBuilder sb = new StringBuilder(str.length());
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
if (!Character.isWhitespace(c)) {
sb.append(c);
}
}
return sb.toString();
}
@Test
public void testTrimAllWhitespace() {
assertEquals("", trimAllWhitespace(""));
assertEquals("", trimAllWhitespace(" "));
assertEquals("", trimAllWhitespace("\t"));
assertEquals("a", trimAllWhitespace(" a"));
assertEquals("a", trimAllWhitespace("a "));
assertEquals("a", trimAllWhitespace(" a "));
assertEquals("ab", trimAllWhitespace(" a b "));
assertEquals("abc", trimAllWhitespace(" a b c "));
}
Alpha, Numeric, and Case Related Methods
11. uppercaseFirstChar(String in)
/**
* Returns the input argument, but ensures the first character is capitalized (if possible).
* @param in the string to uppercase the first character.
* @return the input argument, but with the first character capitalized (if possible).
* @since 1.2
*/
public static String uppercaseFirstChar(String in) {
if (in == null || in.length() == 0) {
return in;
}
int length = in.length();
StringBuilder sb = new StringBuilder(length);
sb.append(Character.toUpperCase(in.charAt(0)));
if (length > 1) {
String remaining = in.substring(1);
sb.append(remaining);
}
return sb.toString();
}
@Test
public void uppercaseFirstCharTest() {
assertEquals("Javaguides", uppercaseFirstChar("javaguides"));
assertEquals("Java", uppercaseFirstChar("java"));
System.out.println(uppercaseFirstChar("javaguides"));
}
12. isAlphaSpace(CharSequence cs)
public static boolean isAlphaSpace(final CharSequence cs) {
if (cs == null) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isLetter(cs.charAt(i)) && cs.charAt(i) != ' ') {
return false;
}
}
return true;
}
@Test
public void testIsAlphaspace() {
assertFalse(isAlphaSpace(null));
assertTrue(isAlphaSpace(""));
assertTrue(isAlphaSpace(" "));
assertTrue(isAlphaSpace("a"));
assertTrue(isAlphaSpace("A"));
assertTrue(isAlphaSpace("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
assertTrue(isAlphaSpace("ham kso"));
assertFalse(isAlphaSpace("1"));
assertFalse(isAlphaSpace("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
assertFalse(isAlphaSpace("_"));
assertFalse(isAlphaSpace("hkHKHik*khbkuh"));
}
13. isAlphanumericSpace(CharSequence cs)
public static boolean isAlphanumericSpace(final CharSequence cs) {
if (cs == null) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isLetterOrDigit(cs.charAt(i)) && cs.charAt(i) != ' ') {
return false;
}
}
return true;
}
@Test
public void testIsAlphanumericSpace() {
assertFalse(StringUtility.isAlphanumericSpace(null));
assertTrue(StringUtility.isAlphanumericSpace(""));
assertTrue(StringUtility.isAlphanumericSpace(" "));
assertTrue(StringUtility.isAlphanumericSpace("a"));
assertTrue(StringUtility.isAlphanumericSpace("A"));
assertTrue(StringUtility.isAlphanumericSpace("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
assertTrue(StringUtility.isAlphanumericSpace("ham kso"));
assertTrue(StringUtility.isAlphanumericSpace("1"));
assertTrue(StringUtility.isAlphanumericSpace("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
assertFalse(StringUtility.isAlphanumericSpace("_"));
assertFalse(StringUtility.isAlphanumericSpace("hkHKHik*khbkuh"));
}
14. isNumeric(CharSequence cs)
public static boolean isNumeric(final CharSequence cs) {
if (isEmpty(cs)) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isDigit(cs.charAt(i))) {
return false;
}
}
return true;
}
@Test
public void testIsNumeric() {
assertFalse(StringUtility.isNumeric(null));
assertFalse(StringUtility.isNumeric(""));
assertFalse(StringUtility.isNumeric(" "));
assertFalse(StringUtility.isNumeric("a"));
assertFalse(StringUtility.isNumeric("A"));
assertFalse(StringUtility.isNumeric("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
assertFalse(StringUtility.isNumeric("ham kso"));
assertTrue(StringUtility.isNumeric("1"));
assertTrue(StringUtility.isNumeric("1000"));
assertTrue(StringUtility.isNumeric("\u0967\u0968\u0969"));
assertFalse(StringUtility.isNumeric("\u0967\u0968 \u0969"));
assertFalse(StringUtility.isNumeric("2.3"));
assertFalse(StringUtility.isNumeric("10 00"));
assertFalse(StringUtility.isNumeric("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
assertFalse(StringUtility.isNumeric("_"));
assertFalse(StringUtility.isNumeric("hkHKHik*khbkuh"));
assertFalse(StringUtility.isNumeric("+123"));
assertFalse(StringUtility.isNumeric("-123"));
}
15. isNumericSpace(CharSequence cs)
public static boolean isNumericSpace(final CharSequence cs) {
if (cs == null) {
return false;
}
final int sz = cs.length();
for (int i = 0; i < sz; i++) {
if (!Character.isDigit(cs.charAt(i)) && cs.charAt(i) != ' ') {
return false;
}
}
return true;
}
@Test
public void testIsNumericSpace() {
assertFalse(StringUtility.isNumericSpace(null));
assertTrue(StringUtility.isNumericSpace(""));
assertTrue(StringUtility.isNumericSpace(" "));
assertFalse(StringUtility.isNumericSpace("a"));
assertFalse(StringUtility.isNumericSpace("A"));
assertFalse(StringUtility.isNumericSpace("kgKgKgKgkgkGkjkjlJlOKLgHdGdHgl"));
assertFalse(StringUtility.isNumericSpace("ham kso"));
assertTrue(StringUtility.isNumericSpace("1"));
assertTrue(StringUtility.isNumericSpace("1000"));
assertFalse(StringUtility.isNumericSpace("2.3"));
assertTrue(StringUtility.isNumericSpace("10 00"));
assertTrue(StringUtility.isNumericSpace("\u0967\u0968\u0969"));
assertTrue(StringUtility.isNumericSpace("\u0967\u0968 \u0969"));
assertFalse(StringUtility.isNumericSpace("hkHKHik6iUGHKJgU7tUJgKJGI87GIkug"));
assertFalse(StringUtility.isNumericSpace("_"));
assertFalse(StringUtility.isNumericSpace("hkHKHik*khbkuh"));
}
File Related String Utility Methods
16. fromBufferedReader(BufferedReader bufferedReader)
public static String fromBufferedReader(BufferedReader bufferedReader) {
StringBuffer sb = new StringBuffer();
try {
String line = bufferedReader.readLine();
while (line != null) {
sb.append(line);
line = bufferedReader.readLine();
if (line != null) {
sb.append("\n");
}
}
} catch (IOException e) {
// replace this with log.error
e.printStackTrace();
}
return sb.toString();
}
17. fromInputStream(InputStream inputStream)
public static String fromInputStream(InputStream inputStream) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
return fromBufferedReader(bufferedReader);
}
String Array related Utility Methods
18. arrayToMap(String[][] array)
public static Map<String, String> arrayToMap(String[][] array) {
Map<String, String> map = new HashMap<String, String>();
for (String[] pair : array) {
if (pair.length > 1) {
// got a pair, add to map
map.put(pair[0], pair[1]);
}
}
return map;
}
19. startsWith(String[] array, String startsWith)
public static String startsWith(String[] array, String startsWith) {
String lcStartsWith = startsWith.toLowerCase();
for (String element : array) {
if (element.toLowerCase().startsWith(lcStartsWith)) {
return element;
}
}
return "";
}
Character related Utility Methods
20. trimLeadingCharacter(String str, char leadingCharacter)
/**
* Trim all occurrences of the supplied leading character from the given {@code String}.
* @param str the {@code String} to check
* @param leadingCharacter the leading character to be trimmed
* @return the trimmed {@code String}
*/
public static String trimLeadingCharacter(String str, char leadingCharacter) {
if (!hasLength(str)) {
return str;
}
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {
sb.deleteCharAt(0);
}
return sb.toString();
}
@Test
public void testTrimLeadingCharacter() {
assertEquals(null, StringUtility.trimLeadingCharacter(null, ' '));
assertEquals("", StringUtility.trimLeadingCharacter("", ' '));
assertEquals("", StringUtility.trimLeadingCharacter(" ", ' '));
assertEquals("\t", StringUtility.trimLeadingCharacter("\t", ' '));
assertEquals("a", StringUtility.trimLeadingCharacter(" a", ' '));
assertEquals("a ", StringUtility.trimLeadingCharacter("a ", ' '));
assertEquals("a ", StringUtility.trimLeadingCharacter(" a ", ' '));
assertEquals("a b ", StringUtility.trimLeadingCharacter(" a b ", ' '));
assertEquals("a b c ", StringUtility.trimLeadingCharacter(" a b c ", ' '));
}
21. trimTrailingCharacter(String str, char trailingCharacter)
/**
* Trim all occurrences of the supplied trailing character from the given {@code String}.
* @param str the {@code String} to check
* @param trailingCharacter the trailing character to be trimmed
* @return the trimmed {@code String}
*/
public static String trimTrailingCharacter(String str, char trailingCharacter) {
if (!hasLength(str)) {
return str;
}
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
@Test
public void testTrimTrailingCharacter() {
assertEquals(null, StringUtility.trimTrailingCharacter(null, ' '));
assertEquals("", StringUtility.trimTrailingCharacter("", ' '));
assertEquals("", StringUtility.trimTrailingCharacter(" ", ' '));
assertEquals("\t", StringUtility.trimTrailingCharacter("\t", ' '));
assertEquals("a", StringUtility.trimTrailingCharacter("a ", ' '));
assertEquals(" a", StringUtility.trimTrailingCharacter(" a", ' '));
assertEquals(" a", StringUtility.trimTrailingCharacter(" a ", ' '));
assertEquals(" a b", StringUtility.trimTrailingCharacter(" a b ", ' '));
assertEquals(" a b c", StringUtility.trimTrailingCharacter(" a b c ", ' '));
}
Other Utility Methods
22. startsWithIgnoreCase( String str, String prefix)
/**
* Test if the given {@code String} starts with the specified prefix,
* ignoring upper/lower case.
* @param str the {@code String} to check
* @param prefix the prefix to look for
* @see java.lang.String#startsWith
*/
public static boolean startsWithIgnoreCase( String str, String prefix) {
return (str != null && prefix != null && str.length() >= prefix.length() &&
str.regionMatches(true, 0, prefix, 0, prefix.length()));
}
23. quote( String str)
/**
* Quote the given {@code String} with single quotes.
* @param str the input {@code String} (e.g. "myString")
* @return the quoted {@code String} (e.g. "'myString'"),
* or {@code null} if the input was {@code null}
*/
public static String quote( String str) {
return (str != null ? "'" + str + "'" : null);
}
24. quoteIfString( Object obj)
/**
* Turn the given Object into a {@code String} with single quotes
* if it is a {@code String}; keeping the Object as-is else.
* @param obj the input Object (e.g. "myString")
* @return the quoted {@code String} (e.g. "'myString'"),
* or the input object as-is if not a {@code String}
*/
public static Object quoteIfString( Object obj) {
return (obj instanceof String ? quote((String) obj) : obj);
}
25. mergeStringArrays(String array1[], String array2[])
/**
* This String utility or util method can be used to merge 2 arrays of
* string values. If the input arrays are like this array1 = {"a", "b" ,
* "c"} array2 = {"c", "d", "e"} Then the output array will have {"a", "b" ,
* "c", "d", "e"}
*
* This takes care of eliminating duplicates and checks null values.
*
* @param values
* @return
*/
public static String[] mergeStringArrays(String array1[], String array2[]) {
if (array1 == null || array1.length == 0)
return array2;
if (array2 == null || array2.length == 0)
return array1;
List<String> array1List = Arrays.asList(array1);
List<String> array2List = Arrays.asList(array2);
List<String> result = new ArrayList<String>(array1List);
List<String> tmp = new ArrayList<String>(array1List);
tmp.retainAll(array2List);
result.removeAll(tmp);
result.addAll(array2List);
return ((String[]) result.toArray(new String[result.size()]));
}
public static void main(String[] args) {
String[] strArray = mergeStringArrays(new String[] {"abc","xyz","pqr"}, new String[] {"ABC","PQR"});
for(String string : strArray){
System.out.println(string);
}
}
abc
xyz
pqr
ABC
PQR
26. endsWithIgnoreCase(String str, String suffix)
/**
* Check a String ends with another string ignoring the case.
*
* @param str
* @param suffix
* @return
*/
public static boolean endsWithIgnoreCase(String str, String suffix) {
if (str == null || suffix == null) {
return false;
}
if (str.endsWith(suffix)) {
return true;
}
if (str.length() < suffix.length()) {
return false;
} else {
return str.toLowerCase().endsWith(suffix.toLowerCase());
}
}
27. startsWithIgnoreCase(String str, String prefix)
/**
* Check a String starts with another string ignoring the case.
*
* @param str
* @param prefix
* @return
*/
public static boolean startsWithIgnoreCase(String str, String prefix) {
if (str == null || prefix == null) {
return false;
}
if (str.startsWith(prefix)) {
return true;
}
if (str.length() < prefix.length()) {
return false;
} else {
return str.toLowerCase().startsWith(prefix.toLowerCase());
}
}
Check out Apache commons lang3 - Which provides highly reusable static utility methods, chiefly concerned with adding value to the java.lang classes.
Related Posts
- Overview of Java Reflection API
- Java Reflection for Classes
- Java Reflection for Methods
- Java Reflection for Fields
- Java Reflection for Constructors
- Java Reflection for Arrays
- Top Reflection Utility Methods
- Java CollectionUtils Class
- Java String Utility Class
- 18 Useful Collections Utility Methods
Comments
Post a Comment
Leave Comment