Firstly: what is the difference between s.equals("")
and "".equals(s)
?
Secondly: what would happen if I was to perform one of these functions? "".substring(1)
or "".charAt(0)
Firstly: what is the difference between s.equals("")
and "".equals(s)
?
Secondly: what would happen if I was to perform one of these functions? "".substring(1)
or "".charAt(0)
Regarding the equals, there is no difference between the two equals variants when it comes to the result. However, the second one is nullsafe. If s
would be null, the first one would throw a NullPointerException, the second variant would just evaluate to false
.
First question: If s
is not null
, then there is no difference. If s
is null
, then s.equals("")
will throw a NullPointerException
while "".equals(s)
will merely return false
.
Second: Both of those will throw an IndexOutOfBoundsException
.
First:
The method of the instance of the class is called for both. So there is no difference in its internals.
It worth noting, however, that "".equals(s)
is not likely to throw an NullPointerException
. It is implemented as follows for the String
class:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
Second:
"".substring(1);
This call would throw an IndexOutOfBoundsException
. From the Java's Documentation the exception occurs: if beginIndex is negative or larger than the length of this String object.
"".charAt(0):
Also, it would throw the exception, and as stated in the previous example: IndexOutOfBoundsException
- if the index argument is negative or not less than the length of this string.