The main benefit of "".equals(s) is you don't need the null check (equals will check its argument and return false if it's null), which you seem to not care about. If you're not worried about s being null (or are otherwise checking for it), I would definitely use s.isEmpty(); it shows exactly what you're checking, you care whether or not s is empty, not whether it equals the empty string
SORRY
I JUST REALISED I MADE A MISTAKE I WANTED TO ASK ABOUT EQUALS("") BUT AT THE SAME TIME I WAS FIGHTING WITH ANOTHER EXCERCISE IN WHICH I HAD TO USE CONTAINS() METHOD AND THIS MESSED UP MY THOUGHTS SORRY FOR WASTING YOUR TIME :/
but still i was able to get some usefull info about contains method so it wasn't as much wasted effort but still sorry
Hi i'm doing(or atleast trying to do) mooc.fi java part 1 course and there in some exercises is required to check for empty input.
So there is my question what is difference between .isEmpty() and .Equals("") because i like to use the first one but in suggested solutions always is used ".Equals("") and i'm wondering is there any rule for using .isEmpty(), maybe it's the matter of optimalization etc. or maybe both are as good
I know it can be stupid question but it's better to ask that and get rid of bad habits in writing code as soon as possible :D
In advance thanks for answers
P.S i hope everything is easy to understand unfortunately my english is still far from good :D
Videos
The main benefit of "".equals(s) is you don't need the null check (equals will check its argument and return false if it's null), which you seem to not care about. If you're not worried about s being null (or are otherwise checking for it), I would definitely use s.isEmpty(); it shows exactly what you're checking, you care whether or not s is empty, not whether it equals the empty string
String.equals("") is actually a bit slower than just an isEmpty() call. Strings store a count variable initialized in the constructor, since Strings are immutable.
isEmpty() compares the count variable to 0, while equals will check the type, string length, and then iterate over the string for comparison if the sizes match.
So to answer your question, isEmpty() will actually do a lot less! and that's a good thing.
I have some config file and it is deployed in many regions. Some regions have certain requirements for example lets say one region needed a username and password (basic auth). The current setup is that each deployment has it's own config file and only the instances where it is needed are these values included in the respective config.xml file.
So I have in my Java code some logic that says
'if this element is in the XML, set the corresponding variable with its value, if not do nothing'
So when I'm trying to see if that value is present or if the tag is empty/blank, which String utility should I use to check?
example code (default option left open as empty string):
if (my_config.getString(USER_ID_ELEMENT, "") != null
& my_config.getString(PASSWORD_ELEMENT, "") != null) {
my_userId = m_config.getString(USER_ID_ELEMENT, "");
my_password = m_config.getString(PASSWORD_ELEMENT, "");Here I'm checking if it is not null, but I don't think it's a very good test since I don't know if an empty XML tag is blank or is empty (i think null isn't even an option)?
StringUtils.isBlank() checks that each character of the string is a whitespace character (or that the string is empty or that it's null). This is totally different than just checking if the string is empty.
From the linked documentation:
Checks if a String is whitespace, empty ("") or null.
StringUtils.isBlank(null) = true StringUtils.isBlank("") = true StringUtils.isBlank(" ") = true StringUtils.isBlank("bob") = false StringUtils.isBlank(" bob ") = false
For comparison StringUtils.isEmpty:
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
Warning: In java.lang.String.isBlank() and java.lang.String.isEmpty() work the same except they don't return true for null.
java.lang.String.isBlank() (since Java 11)
java.lang.String.isEmpty()
The accepted answer from @arshajii is totally correct. However just being more explicit by saying below,
StringUtils.isBlank()
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false
StringUtils.isEmpty
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
Correct way to check for null or empty or string containing only spaces is like this:
if(str != null && !str.trim().isEmpty()) { /* do your stuffs here */ }
You can leverage Apache Commons StringUtils.isEmpty(str), which checks for empty strings and handles null gracefully.
Example:
System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true
Google Guava also provides a similar, probably easier-to-read method: Strings.isNullOrEmpty(str).
Example:
System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true
What about isEmpty() ?
if(str != null && !str.isEmpty())
Be sure to use the parts of && in this order, because java will not proceed to evaluate the second part if the first part of && fails, thus ensuring you will not get a null pointer exception from str.isEmpty() if str is null.
Beware, it's only available since Java SE 1.6. You have to check str.length() == 0 on previous versions.
To ignore whitespace as well:
if(str != null && !str.trim().isEmpty())
(since Java 11 str.trim().isEmpty() can be reduced to str.isBlank() which will also test for other Unicode white spaces)
Wrapped in a handy function:
public static boolean empty( final String s ) {
// Null-safe, short-circuit evaluation.
return s == null || s.trim().isEmpty();
}
Becomes:
if( !empty( str ) )
Use org.apache.commons.lang.StringUtils
I like to use Apache commons-lang for these kinds of things, and especially the StringUtils utility class:
import org.apache.commons.lang.StringUtils;
if (StringUtils.isNotBlank(str)) {
...
}
if (StringUtils.isBlank(str)) {
...
}
I think isEmpty() is a bit more efficient. However a smart compiler may optimize the equals("") call anyway. From the OpenJDK source:
671 public boolean isEmpty() {
672 return count == 0;
673 }
1013 public boolean equals(Object anObject) {
1014 if (this == anObject) {
1015 return true;
1016 }
1017 if (anObject instanceof String) {
1018 String anotherString = (String)anObject;
1019 int n = count;
1020 if (n == anotherString.count) {
1021 char v1[] = value;
1022 char v2[] = anotherString.value;
1023 int i = offset;
1024 int j = anotherString.offset;
1025 while (n-- != 0) {
1026 if (v1[i++] != v2[j++])
1027 return false;
1028 }
1029 return true;
1030 }
1031 }
1032 return false;
1033 }
Also the answer here on whether to use str.isEmpty() or "".equals(str) is spot on:
The main benefit of
"".equals(s)is you don't need the null check (equalswill check its argument and returnfalseif it's null), which you seem to not care about. If you're not worried aboutsbeing null (or are otherwise checking for it), I would definitely uses.isEmpty(); it shows exactly what you're checking, you care whether or notsis empty, not whether it equals the empty string
Yes, use String.isEmpty(). It is cleaner (semantically) (performance is also slightly better, but that would be unnoticable) If the instance can be null, use commons-lang StringUtils.isEmpty(string)
No, absolutely not - because if acct is null, it won't even get to isEmpty... it will immediately throw a NullPointerException.
Your test should be:
if (acct != null && !acct.isEmpty())
Note the use of && here, rather than your || in the previous code; also note how in your previous code, your conditions were wrong anyway - even with && you would only have entered the if body if acct was an empty string.
Alternatively, using Guava:
if (!Strings.isNullOrEmpty(acct))
Use StringUtils.isEmpty instead, it will also check for null.
Examples are:
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false
See more on official Documentation on String Utils.