Java for students logo
Need help with Java programming assignment? Get affordable Java homework help.

Strings comparison code snippet


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

Source code

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");


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

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

            if (str1 == str3)

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


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

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

            if (str1.equals(str3))

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


                  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");


                  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");


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




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



For more information check this: Strings tutorial.