CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ

Control

Control Statements
Boolean expressions
Compare strings

In Java, syrings are compared character by character, starting with the first character and using the Unicode collating sequence. The character-by-character comparison continues until one of the following three conditions is met: a mismatch is found, the last characters have been compared and are equal, or one string is exhausted.

We saw the 2 methods: equals(String) and equalsIgnoreCase(String).

The class String provides the method compareTo to compare objects of the class String.

Syntax

str1.compareTo(str2)
where str1 and str2 are String variables. Moreover, str2 can also be a String constant (literal). this expression returns an integer value as follows:

How to compare strings

  • To test whether two strings contain the same string value, you must call one of the methods of the String object.
  • To test whether a string is null, you can use the equality operator (==) or the inequality operator (!=) with the null keyword.
  • A string object is a reference type, not a primitive data type. So instead of containing data, a string variable refers to (or points to) the data, which is in another location of computer memory.
  • If you use the equality or inequality operator to compare two string variables, Java tests to see whether the two strings refer to the same String object. If they do, the expression is true.
  • Java stores string literals in pools to reduce duplication. So the equality and inequality tests for strings may not work as shown when two String objects are assigned the same literal value.


Expressions that compare two string values

firstName.equals("Frank")       	 // equal to a string literal
firstName.equalsIgnoreCase("Frank")	 // equal to a string literal
firstName.equals("")           		 // equal to an empty string

!lastName.equals("Jones")      		 // not equal to a string literal
!code.equalsIgnoreCase(productCode)  // not equal to another string variable

firstName == null              		 // equal to a null value
firstName != null               	 // not equal to a null value

Code that tests whether two strings refer to the same object

Scanner sc = new Scanner(System.in);
System.out.print("Enter string1: ");
String string1 = sc.next();
System.out.print("Enter string2: ");
String string2 = sc.next();

if (string1 == string2)
           // this will be false no matter what you enter
    System.out.println("string1 = string2");
else
    System.out.println("string1 not = string2");

The code for the String method compareTo

public class StringComparison
{
    public static void main(String[] args)
    {
        String str1 = "Hello";                           //Line 1
        String str2 = "Hi";                              //Line 2
        String str3 = "Air";                             //Line 3
        String str4 = "Bill";                            //Line 4
        String str5 = "Bigger";                          //Line 5

        System.out.println("Line 6: " +
                    "str1.compareTo(str2) evaluates to "
                  +  str1.compareTo(str2));              //Line 6

        System.out.println("Line 7: " +
                    "str1.compareTo(\"Hen\") evaluates to "
                  +  str1.compareTo("Hen"));             //Line 7

        System.out.println("Line 8: " +
                    "str4.compareTo(str3) evaluates to "
                   + str4.compareTo(str3));              //Line 8

        System.out.println("Line 9: " +
                    "str1.compareTo(\"hello\") evaluates to "
                   + str1.compareTo("hello"));           //Line 9

        System.out.println("Line 10: " +
                    "str2.compareTo(\"Hi\") evaluates to "
                   + str2.compareTo("Hi"));              //Line 10

        System.out.println("Line 11: " +
                    "str4.compareTo(\"Billy\") evaluates to "
                   + str4.compareTo("Billy"));           //Line 11

        System.out.println("Line 12: " +
                    "str5.compareTo(\"Big\") evaluates to "
                   + str5.compareTo("Big"));             //Line 12

        System.out.println("Line 13: " +
                    "str1.compareTo(\"Hello \") evaluates to "
                   + str1.compareTo("Hello "));          //Line 13
    }
}

The values, such as -4, -2, 1, and so on, are the differences of the collating sequences of the first unmatched characters of the strings. The only thing we need to know is whether the value is positive, negative, or zero.

Previous | Boolean expressions | Compare primitive data types | Compare strings | Next