简体   繁体   中英

Java String comparison

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 am getting false

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 .

Might be because of whitespace it is coming false

check for this :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM