Copyif (myString != null && !myString.isEmpty()) {
// doSomething
}
As further comment, you should be aware of this term in the equals contract:
From Object.equals(Object):
For any non-null reference value
x,x.equals(null)shouldreturn false.
The way to compare with null is to use x == null and x != null.
Moreover, x.field and x.method() throws NullPointerException if x == null.
java - How to check if my string is equal to null? - Stack Overflow
Question about .isEmpty() and .contains("")
Shorter (efficient) way to check if a string is null or empty?
In Java, should I use (String ) isEmpty() or isBlank() when checking an XML object for an empty value?
Videos
Copyif (myString != null && !myString.isEmpty()) {
// doSomething
}
As further comment, you should be aware of this term in the equals contract:
From Object.equals(Object):
For any non-null reference value
x,x.equals(null)shouldreturn false.
The way to compare with null is to use x == null and x != null.
Moreover, x.field and x.method() throws NullPointerException if x == null.
If myString is null, then calling myString.equals(null) or myString.equals("") will fail with a NullPointerException. You cannot call any instance methods on a null variable.
Check for null first like this:
Copyif (myString != null && !myString.equals("")) {
//do something
}
This makes use of short-circuit evaluation to not attempt the .equals if myString fails the null check.
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