Java String and indexOf

Beginner Algorithms and Data Structures English
Also available: Deutsch
Created by Best · 16.08.2026 at 09:13 UTC

In Java, String.indexOf operates either naively or with JVM optimizations. For teaching purposes, the algorithm matters, not the internal intrinsic.

Characters are UTF-16 code units; be cautious with surrogates in real Unicode texts.

Where used

Everyday API in backends. For fixed patterns, often intrinsically optimized; still, you need to understand complexity and encoding (UTF-16).

Depth

String.indexOf searches for a character or a string from an optional starting position. The result is a position in Java's UTF-16 representation. Characters outside the Basic Multilingual Plane can consist of two code units, which is why the index and perceived character count can differ.

For repeated matches, you must consciously choose the next starting index. A shift by the pattern length will only find non-overlapping occurrences. A shift by one position allows overlaps but requires a special termination rule for an empty search string.

Difficulty levels

  1. Determine positions with and without the starting argument.
  2. Capture overlapping occurrences through appropriate shifting.
  3. Differentiate UTF-16 indices from Unicode code points.

Pitfalls

An unsuccessful result should not be used unchecked as an array or string position. Similarly, loops without secure progression for empty search strings can easily lead to non-termination.

University approvals: 0
Tasks
Question 1

What result does indexOf return when the pattern is missing?

Question 2

How does a loop find overlapping occurrences of a non-empty search string?

Question 3

Implement find using the Java method String.indexOf.

Hint

String.indexOf(String) returns the first index or -1. The method can be called directly on the text reference.

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Algorithms and Data Structures
  • Difficulty: Beginner
  • Completed: 0 users
Creator
Best
Best
BestBuddy