Module 7: Characters and Strings


Objectives

 

By the end of this module, for simple programs, you will be able to:

 


A simple example

 

Consider this simple program:

 

More examples:

 

Operators for char variables:

 


The (useful) relationship between int and char

 

Consider this program:

 

In-Class Exercise 1: What does the above program print?
 

In-Class Exercise 2: Now let's go the other way. Assign the value 100 to an int variable and then from there copy it (with casting) to a char variable. Print the char variable. What is the output?
 

About the conversion:

  • Under the hood, char's are represented by integer codes.

  • It is this code that we see as the number, after casting.
 


Strings

 

Consider this example:

  • A string is a sequence of characters.

  • Notice how a string is declared:

  • Important: String is NOT a reserved word.
           =>
  • String is a special kind of object in the Java language.

  • The (zero or more) characters in a string are enclosed in double-quotes:

 

Java defines a special operator for concatenating strings:

  • This is the same + used for number arithmetic.

  • What's unusual is that one can combine numbers and strings to create longer strings:

  • There is a shortcut operator += to combine assignment and concatenation to the same variable:

    The above is equivalent to: z = z + 2.718.

  • The concatenation operator is particularly useful for System.out.println:

 

In-Class Exercise 3: Modify the code below so that only a single System.out.println is used.

public class ArrayPrint {

    public static void main (String[] argv)
    {
        int i = 5;
        int j = i * i;
        System.out.print ("The square of ");
        System.out.print (i);
        System.out.print (" is ");
        System.out.println (j);
    }

}
 

String methods:

  • Because strings are objects, it is possible to define methods inside them.

  • The Java String object has many such useful methods:

  • Note that length is a method and that it is called using the dot operator with the variable:

  • The method takes no parameters but returns an integer:

  • One can extract a sub-string from a given string using the substring method:

    • Think of the characters in a string being indexed, as in an array, starting with 0.
    • The first parameter to substring is the index of the start of the substring.
    • The second parameter is one more than the index of the last char of the substring.
 

In-Class Exercise 4: Type up the above program (StringMethods) and execute. What goes wrong?
 

To see if two strings are the same, use the equals method in one of the strings to be compared:

 

To compare two strings alphabetically, use the compareTo method:

The compareTo method returns one of three integers:

 

There are other useful methods for strings. Here are three more:

 

More on Java "utility classes":

 


Reading the Javadocs and method overloading

 

An API is an Application Programming Interface, and is a set of methods you can use. Javadocs provides documentation on the APIs that Java supports. Lets understand how to read the APIs a little better.

When reading one of the methods within the Javadocs, do the following:

  1. Read the method name. What do you think it does?
  2. Look at the types and number of parameters. What do you think it does?
  3. Look at the return type. What do you think it does?
  4. Read the English description. What do you think it does?
Take the time to read each component separately, and try and figure out what the method does.

Example:

int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.

 

Other strange things you see in the javadocs:

int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.

int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.

int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

What does this mean?
 

Method overloading

  • Multiple methods with the same name (identifier).

  • Each instance has parameters of different types.

  • The invoked method is the one with the types that match the invocation.

  public class OverloadingExample {
      public static void main(String[] args) {
          myIndexOf("hey");
          myIndexOf('a', 10);
      }
      public static int myIndexOf(int ch) {
          System.out.println("int parameter");
      }
      public static int myIndexOf(int ch, int fromIndex) {
          System.out.println("int parameter, with offset");
      }
      public static int myIndexOf(String str) {
          System.out.println("String parameter");
      }
      public static int myIndexOf(String str, int fromIndex) {
          System.out.println("String parameter, with offset");
      }
  }
 

In-Class Exercise 5: What does the previous code output?
 


Parsing and creative use of APIs

 

Parsing is the act of making sense of a string of text. Java parses the code you write, and interprets it as code. Java is just reading in a large string, and trying to understand its syntax!

Where have you seen strings that your program will want to parse?

 

In-Class Exercise 6:

For the following sets of input, and output strings, which string methods could I use to transform the strings? Use the String javadoc to find methods to help you. Think of these as a puzzle.

  • Input strings: "Hello World!", "Hello Class!", ...
    Desired output: "Goodbye World!", "Goodbye Class!", ...

  • Input strings: "HEllO World!", "heLLo Class!", ...
    Desired output: "goodbye world!", "goodbye class!", ...

  • Input strings: "      asdf", "     jkl;     ", ...
    Desired output: "asdf", "jkl;", ...

  • Input strings: "Lucky number (10)!", "I like (40)!", ...
    Desired output: "10", "40", ...

Please implement and test each transformation as a separate method.
 


 

In-Class Exercise 7: Write a simple program that will determine the winner in a simple card game of "war". Write a method that takes as input a string of the format "4s", which denotes the four of spaces. The suit is denoted by "s" = spades, "d" = diamonds, "h" = hearts, and "c" = clubs. In this exercise, you will write a war method to take two strings as input, and returns 0 if the first string contains a "higher value" card, 1 if the second string does, and -1 if the inputs are not correctly formatted.

The card with the higher numerical value, wins. These values are between 0 and 9. No 10s, aces, kings, queens, or jacks. If two cards have the same value, then the suit breaks the tie. In that case, clubs > diamonds > hearts > spades.

  1. Write a method to check if a card is correctly formatted. How could the data be ill-formatted? formattedCorrectly should check if a String is formatted correctly.
  2. Write the war method.
  3. Challenge: Make your program as small and simple as possible with the fewest possible conditionals.
  public class War {
      public static boolean formattedCorrectly(String s) {
          // Enter your logic here
      }
      public static int war(String a, String b)
      {
          // Enter your logic here
      }
      public static void main(String[] args)
      {
          assert (war("3c", "2c") == 0)   : "3c < 2c?";
          assert (war("3c", "3d") == 0)   : "3c < 3d?";
          assert (war("4s", "3c") == 0)   : "4s < 3c?";
          assert (war("4ss", "3c") == -1) : "improper format check";
          assert (war("4s", "3cc") == -1) : "improper format check";
          assert (war("s9", "3c") == -1)  : "improper format check";
	  // what other checks should we include?
      }
  }
 

In-Class Exercise 8: Use overloaded methods to also provide the following methods:

public static int war(char aNum, char aSuit, char bNum, char bSuit)
aNum and bNum are the numerical component of the cards, and aSuit and bSuit are the suit parts. You should not replicate your logic for the previous method. Instead call that method from this one!

public static int war(int aNum, int bNum)
aNum and bNum are the numerical parts of the two cards. This method assumes that they are of the same suit! Again, don't replicate your logic from before; invoke the previous method from this one.

 


When things go wrong

 

 

In-Class Exercise 9: Identify the errors in the following program and fix them.