Blog Advertising - Advertise on blogs with SponsoredReviews.com

How to Compare Strings in Java

| March 26, 2013

Java-compareto-new Java’s String class includes the compareTo() method, which allows for an easy comparison of two strings. This method returns either -1, 0, or 1, depending on how they compare lexicographically (dictionary order).

-1 is returned when the string on the left side of the “.” is lexicographically before the string within the parentheses.

0 is returned when the two strings are identical.

1 is returned when the string on the left side of the “.” comes lexicographically after the string within the parentheses.

 

 

 

 

[dividers style="3"]

[notice type="support" title="STEP BY STEP" tag="h4"]STEP[/notice]

STEP 1

Create two String instances. Let’s say you have two strings: myString1 and myString2.

STEP 2

Perform a comparison of the two strings. Use myString1.compareTo(myString2) or myString2.compareTo(myString1) in order to get the result.

[dividers style="3"]

[notice type="information" title="TIPS" tag="h4"]

  1. You can use this in a conditional statement in order to output an error message if the strings don’t match:
  2. if (myString1.compareTo(myString2) != 0)
    {
    System.out.println("Error! The strings " + myString1 + " and " + myString2 + " do not match");
    }
  3. If you simply want to check if two strings are equal, you might find it simpler to use the .equals() method:
  4. String myString1 = new String("abc");
    String myString2 = new String("abc");
    if(myString1.equals(myString2))
    {
    System.out.println("The two strings are equal");
    }
  5. NOTE: (myString1 == myString2) would actually return FALSE in this situation. Even though the strings “abc” are equal, myString1 and myString2 are two different instances of String. The “==” operator compares the objects, while the “.equals()” method compares the values of the strings.

[/notice]

[dividers style="3"]

[notice type="warning" title="WARNINGS" tag="h4"]

  1. Do not try to compare strings using a simple == check unless you know what you are doing. This may not return the expected result and can significantly add to your debugging time, especially if you aren’t an experienced Java programmer.
  2. Comparing 2 null strings using the “==” operator returns TRUE, while comparing 2 null strings using .equals() throws an exception.

[/notice]

 

Tags: , , , , , , ,

Category: How-To, Programming Tutor

Comments are closed.

Advertiser Here !!!, iPad, Android phones, BlackBerry, iPod, iPhone, Macs and hundreds more!
Blog Advertising - Advertise on blogs with SponsoredReviews.com