I know they both give same results.
String str="";
System.out.println("".equals(str));
System.out.println(str.equals(""));
Which one is efficient?
I know they both give same results.
String str="";
System.out.println("".equals(str));
System.out.println(str.equals(""));
Which one is efficient?
The first one is called yoda condition and avoid null pointer exception
the second one work fine if str is defined, but you need to handle null condition
Both do the exact same thing, and both are understandable by everyone.
However some programmers consider yoda as bad practice, as it decrease readability. I would also add that sometimes, you want to catch null values, so yoda notation is useless.
In case of empty string that you have passed, there is no difference, both return true
.
But writing: "".equals(str);
is considered as safer than:
str. equals("");
- the second one throws a NullPointerException
if str
is null
, when the first one in that case simply returns false
amd you don't need to deal with checking if str
is null
.