Reputation: 1857
I have the following statement in my java code
System.out.println(cName+" "+pName+" "+cName.equals(pName));
Output is
???????????????? ???????????????? false
The equals should return true right as the two strings have equal number of '?'. But I a m getting false
Upvotes: 3
Views: 241
Reputation: 418585
Those 2 String
s might be equal in their "printed" form on your console, but their content is certainly not equal as proved by the return value of the String.equals()
.
They most likely contain characters which your console cannot display, therefore your console displays '?'
characters for the "undisplayable" characters.
Another possibility could be they contain characters which when printed on the console have no visual appearance. Such characters may be the zero character ('\0'
) and control characters (whose code is less than 32) but this depends on the console how and what it displays.
Note: Even if you open the file where these String
s are stored or initialized and you see the same question marks, it is still possible that your editor is also not able to display the characters and the editor also displays question marks ('?'
) for undisplayable characters or for the characters with no visual appearance.
How to show the difference?
Iterate over the characters of the strings, and print them as int
numbers where you will see the difference:
String s = "Test";
for (int i = 0; i < s.length(); i++)
System.out.println((int) s.charAt(i));
Now if you see the same numbers printed, then yes, you can be sure they are the same, but then String.equals()
would return true
.
Upvotes: 8
Reputation: 1437
Might be because of whitespace it is coming false
check for this :
System.out.println(cName+" "+pName+" "+(cName.trim()).equals(pName.trim()));
Upvotes: 0