AP Computer Science Java: Lesson 4.4
Working with Text - The String Class

Lesson 4.4 - The String Class
Purpose: To learn how to work with text variables using String class methods

Bringing Texty Back!  
We have spent most of our time working with numeric data in this course. Now we tun our attention to working with text - characters, words and sentences. In doing so, we will learn how to work with the String class which includes many useful methods for manipulating text objects.

String Constructors


Sample syntax

  String emptyString = new String();
  String(String value);

  String aGreeting;  
  aGreeting = new String("Hello world");
  aGreeting = "Hello world";  

String Query Methods

Query Method

Sample syntax

  int length();
  String str1 = "Hello!"
len = str1.length(); //len == 6
  char charAt(int index);
  String str1 = "Hello!"
ch = str1.charAt(0); // ch == 'H'
  int indexOf(String str);
  String str2 = "Hi World!"
n = str2.indexOf("World"); // n == 3
  int n = str2.indexOf("Sun"); // n == -1
  int indexOf(int ch);
  String str2 = "Hi World!"
n = str2.indexOf('!'); // n == 8
n = str2.indexOf('T'); // n == -1

String Translate Methods

Translate Method

Sample syntax

  String toLowerCase();
  String greeting = "Hi World!";
  greeting.toLowerCase(); // returns "hi world!"
  String toUpperCase();
  String greeting = "Hi World!";
  greeting.toUpperCase(); // returns "HI WORLD!"
  String trim();
  String needsTrim = " trim me! ";
  needsTrim.trim(); // returns "trim me!"
  String substring(int beginIndex)
  String sample = "hamburger";
  sample.substring(3); // returns "burger"
  String substring(int beginIndex, int endIndex)
  String sample = "hamburger";
  sample.substring(4, 8); // returns "urge"

String Comparison Methods

Comparison Method

Sample syntax

  boolean equals(String anotherString);   String word1 = "dude";
  String word2 = "dude";
    System.out.println("the same");
  boolean equalsIgnoreCase(String anotherString);   String word1 = "dude";
   System.out.println("the same");
  int compareTo(String anotherString)   String word = "dude"
  x = word.compareTo("top"); // x < 0
  x = word.compareTo("dude"); // x == 0
  x = word.compareTo("ask"); // x > 0

One More Thing... A unique characteristic of the
String type is that it supports the "+" operator to concatenate two String objects. For example:

sentence= "I " + "want " + "it " + "all!";
// results in the string "I want it all!"

The "+" operator can also be used to combine add a character to the end of a string:

word="programmer"; // results in the string programmer
word+='s'; // results in the string "programmers"

In closing, The String class has many useful methods, but take care to understand the parameters and return values for each. Only then will you be able to use them wisely. A powerful tool in the hands of a fool can lead to results that are not so cool!

© DanShuster.com