Java string comparison

I have the following statement in my java code

System.out.println(cName+" "+pName+" "+cName.equals(pName));



???????????????? ???????????????? false


For equal numbers, equal numbers are zero. But I am getting false


source to share

2 answers

Those 2 String

may be equal in their "printable" on your console, but their content is of course not equal to the proven return value String.equals()


Most likely they contain characters that your console cannot display, so your console displays characters '?'

for "undisplayable" characters.

Another possibility might be that they contain characters that, when printed to the console, have no visual appearance. Such characters can be null ( '\0'

) and control characters (code less than 32), but this depends on how the console is displayed and how it is displayed.

Note. Even if you open the file in which these String

are saved or initialized and you see the same question marks, it is still possible that your editor also fails to display characters and the editor also displays question marks ( '?'

) for non-transferable characters or characters with no visible external species.

How to show the difference?

Iterate over string characters and print them as int

numbers, where you can 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, then yes, you can be sure they are the same, but then it String.equals()

will return true




Perhaps because of the gap, it comes close false

check it:

System.out.println(cName+" "+pName+" "+(cName.trim()).equals(pName.trim()));




All Articles