File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes String.compareTo(String) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "String.compareTo(String)" Watch "String.compareTo(String)" New topic


Alex Kirk
Ranch Hand

Joined: Aug 13, 2001
Posts: 44
I've got an odd little problem: two strings which appear to the naked eye to be identical are showing up as different when I use java.lang.String.compareTo(String).
The relevant code is:
byte good[] = welcome.getData();
String goodStr = new String(good);
String want = new String("GDNP OK\n\n");
int wasGood = goodStr.compareTo(want);
if (wasGood == 0)
didOK = true;
System.out.println("Got welcome string");
System.out.println("Handshake failed: packet was " + goodStr);
My output reads thusly:

Handshake failed: packet was GDNP OK

Couldn't connect; dying
This doesn't make any sense to me at all. Just in case it's relevant, welcome -- where my first String is coming from -- is a DatagramPacket.
Any ideas why this wouldn't work?
Alex Kirk
Rene Marot

Joined: Jun 27, 2001
Posts: 9
I don't knwon if it comes from the function you use to compare string but you can try to display each byte of your good[] array so you can see what they realy are. You may have an unvisible charater like asc(000) witch is different of a space but sometime looks like on screen.
I agree. Here's the link:
subject: String.compareTo(String)
It's not a secret anymore!