Welcome to Lesson 8!

Learning Objectives
By the end of today's class, you should know...
  • How do you compare chars and use them in the test condition of an if statement?
  • How do you compare Strings and use them in the test condition of an if statement?

  • Midterm 1 - one week from today
    • Study over your old quizzes, in-class activities and homework
    • Material through if statements (Lesson 2 - Lesson 8)
  • Quiz 3 after the break
  • Don't forget to complete Lab 4 on CodeLab

Review Activity

With a partner, answer the following questions:
  • Write one line of code to declare a String variable (name of your choice) and assign it the value $.
  • Write one line of code to declare a char variable (name of your choice) and assign it the value of $.
  • Write a System.out.println statement to print the following message to the console:  Sure! I'll do it. <tab> I "love" boring, repetitive tasks!
  • Given the following string variable:

String statement = "Life is beautiful";

  • Do the following to the String:
    • Print out the String in all capitals
    • Print out the length of the String
    • Print out the first and last character of the String.
  • Write an if statement to check if the value stored in the variable age is equal to 5. If so, print out the age
  • With a partner, identify and correct the 2 mistakes in the code below:

    int guess;
    Scanner input = new Scanner(System.in);
    System.out.print("Enter a guess: ");
    guess = input.nextInt();
    if (guess = 7) {
    } else (guess != 7) {

Comparing Characters and Strings

  • Character data can be evaluated using the relational operators as well.
  • Because characters are primitive types, we can use the 6 relational operators (==, !=, <, >, <=, >=) to compare them.
  • Comparing characters works because Java stores characters as numbers using their Unicode values.
  • Note that letters nearer to the start of the alphabet have lower numerical Unicode values.
  • Thus a numerical comparison can decide the alphabetical order of characters.

Example Program Comparing Characters

public static void main(String[] args) {
    System.out.println("'A' < 'B': " + ('A' < 'B')); System.out.println("'A' > 'B': " + ('A' > 'B')); System.out.println("'A' <= 'Z': " + ('A' <= 'Z')); System.out.println("'X' >= 'Y': " + ('X' >= 'Y')); System.out.println("'X' == 'X': " + ('X' == 'X')); System.out.println("'X' != 'X': " + ('X' != 'X')); }

Comparing Strings - Equals and EqualsIgnoreCase Methods

  • Strings are not primitive types.
  • Therefore, we must use special String methods to compare them.
  • We have already seen one String method for comparison: equals

System.out.println("car".equals("cat")); //prints false

  • Another useful and related String method is equalsIgnoreCase

System.out.println("car".equalsIgnoreCase("CAR")); //prints true

Comparing Strings - CompareTo and CompareToIgnoreCase Methods

  • To compare Strings alphabetically, Java provides two methods: compareTo and compareToIgnoreCase
  • These methods both return a numerical value to indicate which string came first alphabetically.
    • the first string is comes first alphabetically -> negative number as result
    • the strings are equal -> result of 0
    • the second string comes first alphabetically -> positive number as result
  • For example, imagine that we wish to compare "car" and "cat"
  • Alphabetically, "car" comes before "cat":
    c a r
    c a t
  • If we use the compareTo method on these two strings, we will get the following result:

//"car" comes BEFORE "cat":

System.out.println("car".compareTo("cat")); //negative number

  • Also, alphabetically, "car" comes before "card"
    c a r
    c a r d

//"card" comes AFTER "car":

System.out.println("card".compareTo("car")); //positive number

  • CompareToIgnoreCase works the same way, except it ignores upper and lower case characters.
//"Car" comes BEFORE "car":
System.out.println("Car".compareTo("car")); // negative number

//Ignoring case, "Car" and "car" are equal
System.out.println("Car".compareToIgnoreCase("car")); // 0

Table Summarizing compareTo Method

 Alphabetical Order
 Example Result
 First String comes BEFORE second String
 "cat".compareTo("dog"); Negative Number
 Two Strings are EQUAL
 First String comes AFTER second String
Positive Number

Where Do the Numbers Come From?
  • According to Oracle's String API, the numerical value generated by compareTo is the difference in unicode values between the first differing characters in the two Strings.

Example Program Comparing Strings

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String s1, s2;
    System.out.print("Enter two strings: "); s1 = input.next();
    s2 = input.next();
if (s1.compareTo(s2) < 0)
        System.out.println(s1 + " comes before " + s2);
        System.out.println(s2 + " comes before " + s1 + " or is equals to " + s1);

Activity 8.1: Let's Alphabetize! (10 pts)

  • Open up Eclipse and create a new Java project called Alphabetize, with a new class called Alphabetize.java
  • Our program will take in two String inputs from the user, compare then and the output the two Strings in alphabetical order.
  • At the top of your program, declare a string variables called word1.
String word1;
  • Now declare a second String variable called word2.
  • Next, write a System.out.println statement welcoming your user to the program and letting them know that this program will alphabetize two words.
System.out.println("Welcome! Give me two words...\nand I will return them to you in alphabetical order!\n");
  • Run your program to make sure it is giving you the output you expected.
  • Let's prompt the user for the first word and store the result as word1.
System.out.print("Please enter the first word: ");
word1 = input.next(); //assumes new Scanner declared at top of program

  • Do the same for the second word.
  • Now, let's create an if-else statement to determine the ordering of the two words. And, then output the result to our user. The if-else statement will need to use String comparison as discussed above.
  • The code that you have written could be a useful part of a larger program. 
  • Both partners should submit to Canvas when finished.

Wrap up

  • Answer the questions from today's learning objectives

Upcoming Assignments

~Have a Great Weekend!~