Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the better way to check if a String is empty than using String.trim().length() in Java 5/6?

Tags:

java

string

There probably is a method to return the index of the first non-blank char in a String in Java5/6. But I cannot find it any more. A code anylizing tool says it is better than checking String.trim().length().

like image 470
chance Avatar asked Apr 28 '11 13:04

chance


2 Answers

Java 11 introduces the "isBlank" method. See https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html#isBlank()

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

like image 99
David Kerr Avatar answered Nov 15 '22 15:11

David Kerr


I always like to use the Apache Commons StringUtils library. It has isEmpty() and is isBlank() which handles whitespace.

http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html

Not to mention the numerous other helpful methods in that class and the library in general.

like image 44
Jberg Avatar answered Nov 15 '22 17:11

Jberg