Overview

In this reading we’ll look at how Strings are modeled as an array of characters and learn how to access individual characters in a String.

At this point we won’t be learning much, if any, new syntax. Instead our focus will be on learning how to model problems so that they can easily be solved. Part of effectively solving problems is knowing what resources you can use to simplify your solution. In this reading, the focus will be on String methods that will be useful when we start solving problems that focus on text.

Required Reading

Sections 12.1 - 12.2 (pp. 387-394) from the course textbook.

Learning Objectives

BASIC Learning Objectives

Each student will be responsible for learning and demonstrating proficiency in the following objectives PRIOR to the class meeting. The reading quiz will test these objectives.

  1. Write Java code that prints out a String character-by-character using the charAt String method.
  2. Use a backslash escape to create a String that contains add a tab, new line, or special Unicode character.
  3. Use the Double class’ parseDouble method and the Integer class’ parseInt to convert a String to a double or int value.
  4. Create an array of Strings from a single String object using the split method.

ADVANCED Learning Objectives

The following objectives should be mastered by each student DURING and FOLLOWING the class session through active work and practice.

  1. Given a description of a method’s parameters, return type, and functionality, utilize that method inside of a Java program.
  2. Write, read, and trace code that uses String class methods such as charAt, substring and split.

Pre-class Exercises

These exercises are geared towards mastering the BASIC learning objectives listed above. You are expected to submit them before class and it is highly recommended that you complete them before attempting the reading quiz.

For these exercises, you should test your solution using DrJava to see if you are correct.

  1. Given the following String object:

    String myString = "Was it me you're looking for?";

    Write Java code that prints this string out, character-by-character.

  2. Some spreadsheets use a tab-separated value (TSV) format where each column in a row is separated by a “tab”.

    Part A: Write a Java statement that creates a String with the following values separated by tabs. (Hint: See section 12.2.1 for guidance on using tabs in Strings.)

    Part B: Write a Java statement that splits the String you created in Part A into an array of Strings, one for each entry in part A (i.e. “Last Name”, “First Name”, “Email”, and “Grade”).

  3. Consider the following string.

    String numString = "1;5;28;22";

    Part A: Write Java code that splits numString into an array of strings that contain “1”, “5”, “28”, and “22”.

    Part B: Write Java code that converts the String array from Part A into an int array, calculates the average value in this array, then prints out this average value.