Java for students logo
Explore the English language on a new scale using AI-powered English language navigator.

Strings comparison code snippet

Abstract

Code snippet, testing strings for equality and comparing to each other in lexicographic order.

Source code

StringsComparison.java

public class StringsComparison {

      public static void main(String[] args) {

            String str1 = "John";

            String str2 = "Joe";

            String str3 = "Joh";

            str3 += "n";

            System.out.println("str1: \"" + str1 + "\"");

            System.out.println("str2: \"" + str2 + "\"");

            System.out.println("str3: \"" + str3 + "\"");

            // test two strings for equality

            if (str1.equals(str2))

                  System.out.println("str1 and str2 are EQUAL");

            else

                  System.out.println("str1 and str2 are NOT EQUAL");

            // "==" won't work, use equals instead

            if (str1 == str3)

                  System.out.print("str1 == str3");

            else

                  System.out.print("str1 != str3");

            System.out.print(", but ");

            if (str1.equals(str3))

                  System.out.println("str1.equals(str3) is true");

            else

                  System.out.println("str1.equals(str3) is false");

            // compare two strings in lexicographic order

            if (str1.compareTo(str2) < 0)

                  System.out.println("str1 < str2");

            else if (str1.compareTo(str2) > 0)

                  System.out.println("str1 > str2");

            else

                  System.out.println("str1 equals to str2");

            // another example of comparison

            if (str1.compareTo(str3) < 0)

                  System.out.println("str1 < str3");

            else if (str1.compareTo(str3) > 0)

                  System.out.println("str1 > str32");

            else

                  System.out.println("str1 equals to str3");

      }

}

Download StringsComparison.java

Sample run

str1: "John"

str2: "Joe"

str3: "John"

str1 and str2 are NOT EQUAL

str1 != str3, but str1.equals(str3) is true

str1 > str2

str1 equals to str3

 

Extra

For more information check this: Strings tutorial.