콘텐츠로 이동

Unit 1.15: Strings

Scope: CS Awesome 2, Section 1.15

Learning Goals

By the end of this lesson, you should be able to:

  1. Create and combine String objects.
  2. Explain string immutability.
  3. Use indices and the AP Quick Reference methods.
  4. Extract and search for substrings.
  5. Compare strings by content and ordering.

Creating String Objects

A String represents a sequence of characters. String belongs to java.lang, so no import is required.

String first = "hello";
String second = new String("hello");

String literals are the normal, concise way to create strings. The constructor form explicitly creates another object with the same sequence of characters.

String References and Immutability

A String variable stores a reference. A String object is immutable: its character sequence cannot change after creation.

String word = "cold";
word = word.substring(0, 1) + "ard";

The original string object is not edited. New strings are produced, and word is assigned a reference to the final result "card".

A method result must be stored or used if you want to keep it.

String name = "atlas";
name.toUpperCase();          // returned String is discarded
name = name.toUpperCase();   // name now refers to "ATLAS"

Concatenation

+ combines strings and produces a new String. += combines and reassigns.

String code = "A" + "17"; // "A17"
code += "-N";              // "A17-N"

When either operand of + is a String, Java converts the other operand to text.

System.out.println("Total: " + 3 + 4);   // Total: 34
System.out.println("Total: " + (3 + 4)); // Total: 7
System.out.println(3 + 4 + " total");    // 7 total

Evaluation proceeds left to right among + operators unless parentheses change the grouping.

Concatenating an object invokes its toString() representation automatically.

Indices and Length

String indices begin at 0.

String:  C O M P U T E
Index:   0 1 2 3 4 5 6
Length:  7

Valid indices are 0 through length() - 1. Access outside that range causes StringIndexOutOfBoundsException, a form of IndexOutOfBoundsException.

AP Quick Reference String Methods

length()

String text = "COMPUTE";
int n = text.length(); // 7

substring(int from, int to)

Includes index from and excludes index to.

String part = text.substring(1, 4); // "OMP"

The length of the result is to - from.

substring(int from)

Returns from from through the end.

String part = text.substring(4); // "UTE"

To obtain the one-character string at index i:

String one = text.substring(i, i + 1);

indexOf(String target)

Returns the first matching start index, or -1 if not found.

String data = "mississippi";
System.out.println(data.indexOf("iss")); // 1
System.out.println(data.indexOf("xyz")); // -1

Search is case-sensitive.

equals(String other)

Tests whether two strings contain the same sequence of characters.

String a = new String("east");
String b = "east";
System.out.println(a.equals(b)); // true

Do not use == to test string content. == compares reference values rather than the character sequence.

compareTo(String other)

Returns:

  • a negative value when the calling string comes before other;
  • zero when they are equal;
  • a positive value when the calling string comes after other.
System.out.println("apple".compareTo("banana") < 0); // true
System.out.println("same".compareTo("same") == 0);  // true

Use the sign of the result; do not assume the result is exactly -1 or 1.

Common Mistakes

text.substring(2, text.length() + 1); // end index too large
text.substring(4, 2);                 // start after end
text.indexOf("X") > 0                 // misses a match at index 0
text == other                         // compares references, not content
text.substring(1, 1)                  // empty string, not one character

A reliable “found” test is:

text.indexOf(target) >= 0

Practice Missions

Mission 1: Index Map

For String route = "NORTH-27";, write every index under its character. Then find:

  1. the length;
  2. the substring "NORTH";
  3. the one-character string "-";
  4. the substring from index 6 through the end.

Mission 2: Predict Concatenation

Predict the exact output and explain left-to-right evaluation.

System.out.println(2 + 3 + " km");
System.out.println("km " + 2 + 3);
System.out.println("km " + (2 + 3));

Mission 3: Parse an Asset Code

An asset code has the form ZONE-ITEM, such as WEST-4821. Using only indexOf, substring, and length, extract and print the zone and item portions. Do not assume the zone always has four letters.

Mission 4: Content vs. Reference

Predict both results and explain why they can differ.

String x = new String("ready");
String y = "ready";
System.out.println(x == y);
System.out.println(x.equals(y));

Mission 5: Search Contract

Write an expression that is true exactly when target occurs anywhere in text, including index 0. Then give one test where an incorrect > 0 condition fails.

Mission 6: Immutable Rewrite

Given String label = "file.tmp";, create and assign a new value "file.csv" using indexOf and substring. Explain why the original object was not modified.

Key Summary

Concept Core idea
String Immutable object representing characters.
Concatenation + or += creates a new string result.
Index Position from 0 to length() - 1.
substring Copies a selected range into a new string.
indexOf First match index or -1.
equals Compares character content.
compareTo Compares lexicographic ordering by result sign.

Source scope: CS Awesome 2, Unit 1.15