For Programmers: Free Programming Magazines  


Home > Archive > Java Help > January 2007 > Question: Difference between String.equals and String.compareTo????









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Question: Difference between String.equals and String.compareTo????
QQ

2007-01-23, 7:30 pm

Hi All

I was not clear about two methods in String Class:
equals and compareTo

Anybody give a hint?

Thanks a lot.
Steven

Matt Humphrey

2007-01-23, 7:30 pm


"QQ" <chaojiang.au@gmail.com> wrote in message
news:1169592330.288743.226330@h3g2000cwc.googlegroups.com...
> Hi All
>
> I was not clear about two methods in String Class:
> equals and compareTo
>
> Anybody give a hint?


The javadocs spell these out pretty clearly--it's best to read what they say
first. Briefly, equals returns true when the strings have the same
contents. compareTo returns -1 if the first occurs lexigraphically before
the second, +1 if the second is before the first and 0 if they are equal.

Matt Humphrey


Lew

2007-01-23, 7:30 pm

QQ wrote:
> I was not clear about two methods in String Class:
> equals and compareTo
>
> Anybody give a hint?


RTFM: <http://java.sun.com/javase/6/docs/api/>

- Lew
QQ

2007-01-23, 7:31 pm

Hey All

Thanks for that, maybe my question is not quite clear.

I understand the java API stuff, just wonderring am I free to use
either to do string comparation?

e.g. if I just want to check whether two string equals or not, I can
call either method to do it, correct?

Thanks a lot.

Steven

On Jan 24, 9:45 am, "QQ" <chaojiang...@gmail.com> wrote:
> Hi All
>
> I was not clear about two methods in String Class:
> equals and compareTo
>
> Anybody give a hint?
>
> Thanks a lot.
> Steven


Lew

2007-01-23, 7:31 pm

(top-posting reordered.)

QQ wrote:

QQ wrote:[color=darkred]
> Thanks for that, maybe my question is not quite clear.
>
> I understand the java API stuff, just wonderring am I free to use
> either to do string comparation?
>
> e.g. if I just want to check whether two string equals or not, I can
> call either method to do it, correct?


Yes.

- Lew
Eric Sosman

2007-01-26, 10:06 pm

QQ wrote:
> Hey All
>
> Thanks for that, maybe my question is not quite clear.
>
> I understand the java API stuff, just wonderring am I free to use
> either to do string comparation?
>
> e.g. if I just want to check whether two string equals or not, I can
> call either method to do it, correct?


Yes. `s1.equals(s2)' and `s1.compareTo(s2)==0' are
almost equivalent. "Almost" because they behave differently
if s2 is null or is not a String: equals returns false but
compareTo throws an exception.

--
Eric Sosman
esosman@acm-dot-org.invalid
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com