APrep Open the app

AP Computer Science A · Unit 1: Using Objects & Methods

1.11 String Class

Strings are objects, not primitives

A String is a reference type in Java representing a sequence of characters. You create one with a literal (`String s = "hello";`) or the `new` keyword. Strings are immutable — once created, their contents cannot change. Methods that seem to modify a String actually return a brand-new String object.

Common String methods

length() returns the number of characters. charAt(int index) returns the char at a given position (0-indexed). substring(int start, int end) returns characters from start up to (not including) end — if end is omitted, it goes to the end of the string. indexOf(String str) returns the index of the first occurrence, or -1 if not found.

Comparing Strings

Use equals() to compare String *contents* for equality — always prefer this over `==`, which compares object references (memory addresses) and can give misleading results. compareTo() returns a negative, zero, or positive int based on lexicographic (dictionary) order, useful for sorting.

Key terms

String immutability
Once created, a String's contents can't be changed; methods return new String objects instead of modifying the original.
length()
Returns the number of characters in a String.
substring(start, end)
Returns characters from index start up to (not including) index end.
equals() vs ==
equals() compares String content/characters; == compares object references (memory addresses).
compareTo()
Returns negative, zero, or positive int indicating lexicographic order between two Strings.

Try an AP-style question

What is "computer".substring(2, 5)?

  1. "mpu"
  2. "mput"
  3. "mpute"
  4. "omp"
Show the answer

A. Indexes 2, 3, 4.

Practice 8 AP-style questions with instant explanations, flashcards and spaced review.

Study 1.11 free in APrep