String s1 = "a";
System.out.println(s1.equals('a'));
Output:
False
Can anyone please explain me why is it coming false even though the string s1 has only one character 'a'.
To understand why are you getting false, which is unexpected for you. First, you need to understand your code
s1.equals('a')
s1 is a String and 'a' is Character, so you are comparing two different object.
As per documentation :
trueif the given object represents aStringequivalent to this string,falseotherwise
Now, come back to equals method implementation in String class.
// some more code
if (anObject instanceof String) {
// code here
// some more code
}
return false;
You could see, it is checking if object, which you passed is type of String ?? In your case, No, it is Character. So, you are getting false as a result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With