This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Java String comparison dilemma Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Java String comparison dilemma" Watch "Java String comparison dilemma" New topic

Java String comparison dilemma

Kaverappa Prabhakar
Ranch Hand

Joined: Aug 18, 2009
Posts: 43
In the code below, I was expecting System.out.println would not get executed but it does. If I switch the key and date position in CompareTo code then it won't execute.

Could any one explain to me why it is so?

Christophe Verré

Joined: Nov 24, 2005
Posts: 14688

Both key and date are Strings. Did you check the API for the compareTo method in the java.lang.String class ? What happens when you compare "02009" to "12008", and "12008" to "02009" ?

[My Blog]
All roads lead to JavaRanch
Rob Spoor

Joined: Oct 27, 2005
Posts: 19908

You should consider using a (Simple)DateFormat to parse the strings into Date objects, then compare those.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Java String comparison dilemma