Java • Syntax and Core Types

String Methods — Use String methods (substring, indexOf, equals, compareTo) (intro)

Master the essential String methods that let you search, compare, and extract text in Java programs.

Java programming emblem with a coffee cup, code braces, and terminal
Inside this lesson 10 sections 5 questions 6 figures

SECTION 1

Historical Context & Motivation

Nearly every program you use — from search engines to social media apps — needs to manipulate text. In the early days of programming, working with text was surprisingly difficult. Languages like C required developers to manage individual characters stored in raw memory arrays, which led to frequent bugs and security vulnerabilities. Java was designed from the start to make text processing safer and more convenient by providing a built-in String class packed with powerful methods.

1972 • C Language & Character Arrays

The C programming language represented text as null-terminated character arrays. Programmers had to manually track string length and memory allocation, which was error-prone and tedious.

1983 • C++ Introduces std::string

C++ added a string class to its standard library, wrapping character arrays in a safer abstraction. This inspired later language designers to make strings first-class citizens.

1995 • Java Launches with java.lang.String

Java 1.0 shipped with an immutable String class that included methods like substring, indexOf, equals, and compareTo. Strings became objects with built-in behaviors, not just data.

2004 • Java 5 & Enhanced String Features

Java 5 added autoboxing, generics, and the StringBuilder class. String formatting with printf-style methods made text manipulation even more flexible.

The central question this lesson addresses is: once you have a String in Java, how do you search within it, extract portions of it, and compare it to other Strings? The four methods we'll explore — substring, indexOf, equals, and compareTo — give you the tools to answer all three.

SECTION 2

Core Principles & Definitions

Before diving into individual methods, you need to understand a few foundational ideas about how Java handles Strings. A String in Java is an object — not a primitive type like int or double. Because it's an object, it comes with methods you can call using dot notation, such as myString.length(). Strings are also immutable, meaning once a String is created, its characters can never be changed. Every method that seems to modify a String actually returns a brand-new String.

1

Zero-Based Indexing

Characters in a String are numbered starting at 0, not 1. In "Hello", 'H' is at index 0 and 'o' is at index 4.
2

Immutability

Strings cannot be changed after creation. Methods like substring() return a new String rather than modifying the original. This makes Strings safe to share across your program.
3

Reference vs. Value Comparison

The == operator checks if two variables point to the same object in memory. The equals() method checks if two Strings contain the same characters — which is almost always what you want.
4

Lexicographic Ordering

The compareTo() method compares Strings based on Unicode character values, similar to alphabetical order. It returns a negative number, zero, or a positive number.
✦

KEY TAKEAWAY

Think of a String like a row of lockers in a hallway. Each locker has a number (its index, starting at 0) and holds exactly one character. You can look at any locker and read its contents, but you can't swap out what's inside — the hallway is locked after construction. The four methods we're learning are like tools for this hallway: indexOf finds which locker holds a certain item, substring copies a section of lockers into a new hallway, and equals/compareTo compare two hallways to see if they match.

SECTION 3

Visualizing String Indexing & Methods

The diagram below shows how a String is stored as an indexed sequence of characters and illustrates how indexOf() and substring() operate on those indices. Pay close attention to the index numbers — they are the key to understanding every String method.

String Indexing: "Computer"Index:01234567ComputerindexOf('p') → 3Returns index 3 where 'p' is foundsubstring(3, 6) → "put"Extracts indices 3, 4, 5 (inclusive start, exclusive end)beginIndex = 3endIndex = 6length() → 8Total characters: 8 • Valid indices: 0 through 7Last valid index = length() − 1
The character boxes show each character of "Computer" with its zero-based index above. The pink arrow demonstrates indexOf('p') returning 3. The amber dashed box shows substring(3, 6) extracting characters at indices 3, 4, and 5 to produce "put".

Notice two critical details in this diagram. First, the index of the last character ('r') is 7, which is length() − 1. This is always the case, because indexing starts at 0. Second, substring(3, 6) includes index 3 but excludes index 6. This inclusive-start, exclusive-end pattern is extremely common throughout Java and many other languages. It might feel odd at first, but it has a nice property: the number of characters extracted equals endIndex − beginIndex (6 − 3 = 3 characters).

SECTION 4

How Each Method Works

substring(int beginIndex, int endIndex)

The substring method extracts a portion of a String. It takes two parameters: beginIndex (the first character to include) and endIndex (the first character to exclude). There is also a one-parameter version, substring(beginIndex), which returns everything from beginIndex to the end of the String.

SUBSTRING LENGTH

resultLength=endIndex−beginIndexresultLength = endIndex − beginIndex

For "Hello".substring(1, 4), resultLength = 4 − 1 = 3, so the result is "ell".

indexOf(String target)

The indexOf method searches the String from left to right and returns the index of the first occurrence of the target. If the target is not found, it returns −1. You can pass either a single character or a String as the target. For example, "banana".indexOf("nan") returns 2 because the substring "nan" starts at index 2.

equals(Object other)

The equals method compares the character content of two Strings and returns true if every character matches (same characters in the same order). This is different from ==, which checks whether two variables refer to the exact same object in memory. A common beginner mistake is to write if (name == "Alice") when you should write if (name.equals("Alice")). The == version might work sometimes due to Java's String pool optimization, but it is unreliable and should be avoided for String comparison.

compareTo(String other)

The compareTo method performs lexicographic comparison — essentially dictionary-style ordering based on Unicode values. It returns an integer: a negative value if the calling String comes before the argument, zero if they are equal, and a positive value if the calling String comes after the argument. For example, "apple".compareTo("banana") returns a negative number because 'a' comes before 'b' in the alphabet.

⚠

Watch Out: Case Sensitivity

All four methods are case-sensitive. "Hello".equals("hello") returns false because uppercase 'H' and lowercase 'h' are different characters. If you need case-insensitive comparison, use equalsIgnoreCase() or compareToIgnoreCase().

SECTION 5

Method Signatures & Return Values

The table below summarizes the four String methods covered in this lesson. Keep it handy as a quick reference while you practice. Understanding the return type of each method is essential — some return Strings, some return integers, and one returns a boolean.

MethodReturn TypeReturnsExample
substring(begin, end)StringNew String from begin (inclusive) to end (exclusive)"Java".substring(1,3) → "av"
substring(begin)StringNew String from begin to end of the String"Java".substring(2) → "va"
indexOf(target)intIndex of first occurrence, or −1 if not found"Java".indexOf("av") → 1
equals(other)booleantrue if same characters; false otherwise"Hi".equals("Hi") → true
compareTo(other)intNegative, zero, or positive based on lexicographic order"A".compareTo("B") → −1

Summary of the four key String methods

equals() vs == : What's the Difference?String a = new String("Hi");String b = new String("Hi");String c = "Hi";String d = "Hi";Memory (Heap):"Hi"Object 1 (a)"Hi"Object 2 (b)"Hi"Shared Pool (c, d)Using == (reference check)a == b → false ✗c == d → true ✓ (pool)Using .equals() (content check)a.equals(b) → true ✓c.equals(d) → true ✓✦ Best PracticeAlways use .equals() to compare String content. The == operator is unreliable for Strings.
When you use new String(), Java creates separate objects in memory, so == returns false even if the content matches. The equals() method always compares the actual characters, making it the reliable choice.

SECTION 6

Worked Example

Let's work through a realistic scenario. Suppose you receive an email address as a String, and you need to extract the username (everything before the '@' sign) and the domain (everything after it). You also need to verify the email matches an expected value.

Extract Username and Domain from an Email

  1. 1

    Step 1 — Declare the String

    We start with the email stored in a String variable: String email = "student@school.edu"; The String has 18 characters with indices from 0 to 17.
  2. 2

    Step 2 — Find the '@' symbol with indexOf

    Call int atPos = email.indexOf("@"); to locate the '@' character. Java scans left to right and finds '@' at index 7.
    atPos = 7
  3. 3

    Step 3 — Extract the username with substring

    To get everything before the '@', use String user = email.substring(0, atPos); This extracts characters at indices 0 through 6 (inclusive start, exclusive end at index 7).
    user = "student"
  4. 4

    Step 4 — Extract the domain with substring

    To get everything after the '@', use String domain = email.substring(atPos + 1); By passing atPos + 1 (which is 8), we skip the '@' itself and capture from index 8 to the end.
    domain = "school.edu"
  5. 5

    Step 5 — Verify with equals and compareTo

    Check if the domain matches an expected value: domain.equals("school.edu") returns true. To determine alphabetical ordering, user.compareTo("teacher") returns a negative number because 's' (in "student") comes before 't' (in "teacher") alphabetically.
    equals → true, compareTo → negative (student < teacher)

SECTION 7

Common Pitfalls & Best Practices

Even experienced programmers stumble when working with String methods. The table below lists the most common mistakes and the correct approach. Study these carefully — they appear frequently on AP exams and in real-world code reviews.

PitfallWhat Goes WrongCorrect Approach
Using == to compare StringsCompares memory addresses, not content. May return false even when Strings have identical characters.Always use .equals() for content comparison.
Off-by-one errors in substring()Forgetting that endIndex is exclusive, leading to missing or extra characters.Remember: start is inclusive, end is exclusive. Count on your fingers if needed.
StringIndexOutOfBoundsExceptionPassing an index < 0 or ≥ length() to substring or charAt causes a runtime crash.Check that your index is within valid range (0 to length() − 1).
Ignoring case sensitivity"Yes".equals("yes") returns false unexpectedly.Use equalsIgnoreCase() or convert both to lowercase first.
Forgetting indexOf returns −1Using the result of indexOf directly in substring without checking for −1 causes errors.Always check if indexOf() != -1 before using the result.

Common String method pitfalls and how to avoid them

✦

KEY TAKEAWAY

Think of == versus equals() like comparing two identical textbooks. The == operator is like asking, "Are these the exact same physical copy?" while equals() asks, "Do these books have the same words on every page?" Two separate copies of the same book are equals() but not ==. In nearly every real situation, you care about the content, not the identity of the object.

SECTION 8

Connection to Advanced String Topics

The four methods in this lesson form the foundation for all String manipulation in Java. As you advance, you'll encounter more powerful tools that build directly on these concepts. Understanding how they relate will help you choose the right approach for increasingly complex problems.

Introductory MethodAdvanced ExtensionWhat It Adds
indexOf()lastIndexOf(), contains(), Regular ExpressionsSearch from the end, check for presence without index, or match complex patterns
substring()split(), replace(), trim()Break a String into an array, substitute characters, or remove whitespace
equals()equalsIgnoreCase(), contentEquals()Case-insensitive comparison, or comparison with StringBuffer/StringBuilder
compareTo()Comparable interface, ComparatorCustom sorting logic for collections of objects, not just Strings

How introductory methods connect to advanced topics

Another important advanced topic is the StringBuilder class. Because Strings are immutable, concatenating many Strings in a loop creates numerous temporary objects. StringBuilder provides a mutable alternative that is more efficient for building large Strings piece by piece. You'll likely encounter this in AP Computer Science A or in performance-sensitive applications.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain why "Hello".substring(0, 5) returns "Hello" even though the last valid index is 4, not 5. Why doesn't this cause an error?
Show answer
The endIndex parameter in substring() is exclusive — it specifies the first index NOT to include. The valid range for endIndex is 0 through length() (which is 5 for "Hello"). So substring(0, 5) means "start at index 0 and stop before index 5," which captures all five characters. It doesn't cause an error because endIndex is allowed to equal length(); it just means "go to the end." This is different from trying to access index 5 with charAt(5), which would throw an exception.

Question 2: BASIC CALCULATION

Given String s = "programming";, what does each expression return? (a) s.indexOf("gram") (b) s.substring(3, 7) (c) s.indexOf("z")
Show answer
(a) s.indexOf("gram") returns 3. The substring "gram" begins at index 3 in "programming" (p-r-o-g-r-a-m-m-i-n-g, with 'g' at index 3). (b) s.substring(3, 7) returns "gram". It starts at index 3 (inclusive) and stops before index 7 (exclusive), extracting characters at indices 3, 4, 5, and 6. (c) s.indexOf("z") returns −1 because the character 'z' does not appear anywhere in "programming". Whenever indexOf fails to find the target, it returns −1 as a signal.

Question 3: INTERMEDIATE

Write a Java expression (or short code snippet) that extracts the file extension from a filename stored in String filename = "report.pdf";. Your result should be "pdf" (without the dot). Use indexOf and substring.
Show answer
First, find the position of the dot: int dotPos = filename.indexOf("."); This returns 6. Then extract everything after the dot: String ext = filename.substring(dotPos + 1); By using dotPos + 1 (which is 7), we skip the dot itself and get "pdf". In a robust program, you should also check that dotPos != -1 before calling substring, in case the filename has no extension.

Question 4: APPLIED

A program receives user input and needs to determine if it starts with "http://" or "https://". Using only substring, equals, and indexOf, write code that prints "Secure" if the URL starts with "https://", "Not secure" if it starts with "http://", and "Invalid" otherwise. Assume String url = "https://example.com";
Show answer
One approach is to extract the beginning of the URL and compare: if (url.substring(0, 8).equals("https://")) { System.out.println("Secure"); } else if (url.substring(0, 7).equals("http://")) { System.out.println("Not secure"); } else { System.out.println("Invalid"); } We use substring(0, 8) to grab the first 8 characters and compare them to "https://" using equals(). If that fails, we try substring(0, 7) against "http://". Note that in production code you'd want to handle the case where the URL is shorter than 7 or 8 characters to avoid a StringIndexOutOfBoundsException, but this demonstrates the core method usage.

Question 5: CRITICAL THINKING

Consider two Strings: String a = "apple"; and String b = "Banana"; (a) Will a.compareTo(b) return a positive or negative number? Explain why. (b) Does this match alphabetical order as you would expect in a dictionary? Explain the discrepancy.
Show answer
(a) a.compareTo(b) returns a positive number. This is because compareTo uses Unicode values, and all uppercase letters (A=65 through Z=90) have lower Unicode values than all lowercase letters (a=97 through z=122). So 'a' (97) is greater than 'B' (66), making "apple" come AFTER "Banana" in compareTo's ordering. (b) This does NOT match normal dictionary order, where "apple" would come before "banana" regardless of capitalization. The discrepancy arises because compareTo is case-sensitive and treats uppercase as "less than" lowercase. To get true alphabetical ordering, you would use compareToIgnoreCase() or convert both Strings to the same case before comparing. This is a crucial detail when implementing sorting algorithms for user-facing data.

SUMMARY

Lesson Summary

Summary

Java's String class provides built-in methods for manipulating text safely and efficiently. The substring() method extracts a portion of a String using zero-based indexing with an inclusive start and exclusive end. The indexOf() method searches for a character or substring and returns its position, or −1 if not found. For comparing Strings, always use equals() to check if two Strings contain the same characters — never ==, which only checks object identity.

The compareTo() method enables lexicographic ordering by returning a negative, zero, or positive integer. Remember that all four methods are case-sensitive and that Strings are immutable — every operation returns a new String without modifying the original. These four methods form the backbone of text processing in Java and appear frequently on the AP Computer Science A exam. Mastering them prepares you for advanced topics like regular expressions, string parsing, and custom sorting.

Varsity Tutors • Java • String Methods — Use String methods (substring, indexOf, equals, compareTo) (intro)