Back

Activity 4.9 — String Methods

divider

Introduction

Activity 4-9

String Methods

Strings are objects

  • String is a class.
  • A String variable stores a String object.
  • Objects have methods you can call with dot notation.
// Strings are objects
String word = "hello";
// Objects have methods
word.length();
word.toUpperCase();
word.substring(1, 3);

One easy confusion

  • Arrays use length
  • Strings use length()
// Arrays vs Strings
arr.length // array length field
word.length() // String length method

substring

  • substring(start, end) includes the start index.
  • It does not include the end index.
  • substring(start) goes from start to the end of the string.
// substring(start, end)
// start is included
// end is NOT included
String s = "computer";
System.out.println(s.substring(0, 3)); // com

indexOf

  • Finds the first position of a character or substring.
  • If nothing is found, it returns -1.
// indexOf returns the first match
String s = "banana";
System.out.println(s.indexOf("a")); // 1
System.out.println(s.indexOf("na")); // 2
System.out.println(s.indexOf("z")); // -1

Comparing Strings

  • Use equals to test if two strings have the same text.
  • Do not use == for String comparison on the AP exam.
// equals vs ==
String a = "cat";
String b = "cat";
// Use equals for String comparison
a.equals(b);

compareTo

  • Used for alphabetical comparison.
  • Negative means “comes before.”
  • Positive means “comes after.”
  • Zero means the strings are equal.
// compareTo
"a".compareTo("b") // negative
"b".compareTo("a") // positive
"a".compareTo("a") // 0

Strings are immutable

  • String methods do not change the original String.
  • They return a new String instead.
  • If you want the change, assign the result to a variable.
// Strings are immutable
String s = "hello";
s.toUpperCase(); // does NOT change s
s = s.toUpperCase(); // reassign if you want the change

Today's goals

  • Use common AP String methods correctly.
  • Extract pieces of text with substring.
  • Search for text with indexOf.
  • Compare Strings with equals and compareTo.

'F' → Fullscreen

Objectives

  • icon Use common String methods including length(), substring(), and indexOf().
  • icon Compare strings using equals() and compareTo().
  • icon Explain why Strings are immutable.
  • icon Solve small text-processing problems using String methods.
divider

Activity Tasks

  • icon Create a new project named Activity4-9-StringMethods.
  • icon Complete Tasks 1-5.
  • icon Use the figures as references while you work.

Figures: Reference Examples

Figure 1 — Common String methods
// Figure 1 — Common String methods
public class Program
{
public static void main(String[] args)
{
String word = "programming";
System.out.println(word.length()); // 11
System.out.println(word.substring(0, 4)); // prog
System.out.println(word.substring(3)); // gramming
System.out.println(word.indexOf("g")); // 3
System.out.println(word.toUpperCase()); // PROGRAMMING
}
}
Figure 2 — Comparing Strings
// Figure 2 — Comparing Strings correctly
public class Program
{
public static void main(String[] args)
{
String a = "cat";
String b = "cat";
System.out.println(a.equals(b)); // true
System.out.println(a.compareTo(b)); // 0
System.out.println(a.compareTo("dog")); // negative
}
}
Figure 3 — Immutability
// Figure 3 — Strings are immutable
public class Program
{
public static void main(String[] args)
{
String word = "hello";
word.toUpperCase();
System.out.println(word); // still hello
word = word.toUpperCase();
System.out.println(word); // now HELLO
}
}
Figure 4 — substring + indexOf pattern
// Figure 4 — A useful pattern with substring + indexOf
public class Program
{
public static void main(String[] args)
{
String fullName = "Ada Lovelace";
int spaceIndex = fullName.indexOf(" ");
String firstName = fullName.substring(0, spaceIndex);
String lastName = fullName.substring(spaceIndex + 1);
System.out.println(firstName);
System.out.println(lastName);
}
}

Task 1: String Analyzer

Task 1 — String Analyzer
// Task 1 — String Analyzer
//
// Create a String named word.
// Then print:
// 1) The word
// 2) Its length
// 3) The first character
// 4) The last character
// 5) The uppercase version
//
// Hint:
// first character: substring(0, 1)
// last character: substring(word.length() - 1)
public class Program
{
public static void main(String[] args)
{
String word = "computer";
System.out.println("Word: " + word);
System.out.println("Length: " + word.length());
System.out.println("First character: " + word.substring(0, 1));
System.out.println("Last character: " + word.substring(word.length() - 1));
System.out.println("Uppercase: " + word.toUpperCase());
}
}

Task 2: Initials Generator

Task 2 — Initials Generator
// Task 2 — Initials Generator
//
// Create a String fullName with a first and last name.
// Example: "Grace Hopper"
//
// Use indexOf and substring to print the initials like:
// G.H.
//
// Steps:
// 1) Find the space index
// 2) Get the first letter of the first name
// 3) Get the first letter of the last name
// 4) Print them with periods
public class Program
{
public static void main(String[] args)
{
String fullName = "Grace Hopper";
int spaceIndex = fullName.indexOf(" ");
String firstInitial = fullName.substring(0, 1);
String lastInitial = fullName.substring(spaceIndex + 1, spaceIndex + 2);
System.out.println(firstInitial + "." + lastInitial + ".");
}
}

Task 3: Username Generator

Task 3 — Username Generator
// Task 3 — Username Generator
//
// Create a String fullName.
// Generate a username using:
// - the first letter of the first name
// - the full last name
// - all lowercase
//
// Example:
// "Ada Lovelace" -> alovelace
//
// Use substring, indexOf, and toLowerCase.
public class Program
{
public static void main(String[] args)
{
String fullName = "Ada Lovelace";
int spaceIndex = fullName.indexOf(" ");
String firstInitial = fullName.substring(0, 1);
String lastName = fullName.substring(spaceIndex + 1);
String username = (firstInitial + lastName).toLowerCase();
System.out.println("Username: " + username);
}
}

Task 4: Word Finder

Task 4 — Word Finder
// Task 4 — Word Finder
//
// Create a sentence String.
// Use indexOf to search for a target word.
//
// Print:
// 1) The sentence
// 2) The index of the target word
// 3) A message saying whether it was found
//
// Remember:
// indexOf returns -1 if the word is not found.
public class Program
{
public static void main(String[] args)
{
String sentence = "The quick brown fox jumps over the lazy dog";
String target = "fox";
int index = sentence.indexOf(target);
System.out.println("Sentence: " + sentence);
System.out.println("Index of target: " + index);
if (index == -1)
{
System.out.println("Target not found.");
}
else
{
System.out.println("Target found.");
}
}
}

Task 5: String Comparison Mini-Challenge

Task 5 — Comparison Practice
// Task 5 — String Method Practice Mini-Challenge
//
// Create two Strings and do all of the following:
// 1) Check if they are equal using equals
// 2) Compare them alphabetically using compareTo
// 3) Print both lowercase
// 4) Print both uppercase
//
// Suggested values:
// "Apple"
// "banana"
public class Program
{
public static void main(String[] args)
{
String a = "Apple";
String b = "banana";
System.out.println("Equals? " + a.equals(b));
System.out.println("compareTo: " + a.compareTo(b));
System.out.println("a lowercase: " + a.toLowerCase());
System.out.println("b lowercase: " + b.toLowerCase());
System.out.println("a uppercase: " + a.toUpperCase());
System.out.println("b uppercase: " + b.toUpperCase());
}
}
divider

Sample Output

Your program output should something similar to the sample output below.

Sample Output
Word: computer
Length: 8
First character: c
Last character: r
Uppercase: COMPUTER
G.H.
Username: alovelace
Sentence: The quick brown fox jumps over the lazy dog
Index of target: 16
Target found.
Equals? false
compareTo: -33
a lowercase: apple
b lowercase: banana
a uppercase: APPLE
b uppercase: BANANA
divider

Reflection Questions

You may write your reflection answers as comments at the bottom of your code.

  1. Why should you use equals() instead of == for Strings?
  2. What does indexOf() return when the text is not found?
  3. Why does substring(0, 3) return only the first three characters?
  4. What does it mean that Strings are immutable?
  5. How is compareTo() different from equals()?
divider

Submission

Submit your activity and reflection answers to the appropriate dropbox.

Activity Complete