Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is String sequence of characters in Java?

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'.

like image 254
Aashit Garodia Avatar asked May 13 '26 06:05

Aashit Garodia


1 Answers

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 :

true if the given object represents a String equivalent to this string, false otherwise

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.

like image 80
Ravi Avatar answered May 14 '26 18:05

Ravi