Back to Blog
Java

Java String startsWith: Syntax and Common Pitfalls

java string startswith: Learn how to use Java String startsWith for prefix checks, including offset, case sensitivity, edge cases, and performance considerations.

JavaStringstartsWithString ComparisonCase SensitivityPerformance
Java code snippet showing a string being checked with startsWith, with a magnifying glass highlighting the prefix comparison.

java string startswith requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.

The startsWith method in Java's String class checks whether a string begins with a specified prefix. It returns a boolean and is a common tool for validation, parsing, and routing logic. The method is straightforward, but several details affect its behavior in real-world code. This article covers the syntax, the optional offset parameter, edge cases, performance characteristics, and how startsWith compares with related methods.

Basic Syntax and Usage

The simplest form of startsWith takes a single String argument and returns true if the string begins with that exact sequence of characters. Here is a minimal example:

String url = "https://example.com"; if (url.startsWith("https")) { System.out.println("Secure connection"); }

The method is case-sensitive. "https".startsWith("HTTP") returns false. There is no locale-dependent behavior because the comparison is based on Unicode code points, not locale-specific collation rules. This makes startsWith predictable across different environments.

The method is defined in the String class and has been available since Java 1.0. It does not modify the original string and is safe to call on null references only if you guard against null first—calling startsWith on a null reference throws a NullPointerException.

Using the Offset Parameter

The overloaded version startsWith(String prefix, int offset) checks whether the substring beginning at the given index starts with the specified prefix. The offset is zero-based. This is useful when you need to inspect a string at a known position without creating a substring.

String filename = "report_final_2024.pdf"; if (filename.startsWith("final", 7)) { System.out.println("This is a final version"); }

In this example, the character at index 7 is 'f', so the check succeeds. The offset must be between 0 and the string length. If the offset is negative or greater than the string length, the method returns false rather than throwing an exception. This behavior is defined in the Java API and is worth remembering when you handle dynamic offsets.

The offset variant is particularly handy when parsing fixed-format records or when you want to avoid the overhead of substring to create a temporary string.

Handling Null and Empty Arguments

Passing a null prefix to startsWith always throws a NullPointerException. There is no overload that accepts a null prefix and returns false. If your code may receive a null prefix, guard it explicitly:

if (prefix != null && text.startsWith(prefix)) { // safe }

An empty string ("") is a valid prefix. startsWith("") always returns true because every string contains the empty string at its start. This is consistent with the definition of a prefix and is rarely a problem, but it can lead to subtle bugs if you assume a non-empty prefix.

When the string itself is empty, startsWith("") returns true, and startsWith(prefix) with a non-empty prefix returns false. The offset variant behaves similarly: "".startsWith("", 0) returns true, while "".startsWith("a", 0) returns false.

Comparing startsWith with Related Methods

Java provides several methods for substring and pattern matching. Choosing the right one depends on the exact requirement. The table below compares startsWith with common alternatives.

MethodPurposeCase-sensitiveRegex supportPerformance characteristics
startsWith(prefix)Checks prefix at start of stringYesNoO(prefix length), no regex overhead
contains(sequence)Checks if sequence appears anywhereYesNoO(n), scans entire string
regionMatches(...)Compares regions with optional case-insensitivityConfigurableNoO(region length)
matches(regex)Checks if entire string matches regexDepends on regexYesHigher overhead due to regex compilation
indexOf(prefix)Finds first occurrence of prefixYesNoO(n), returns index or -1

Use startsWith when you need a simple, fast prefix check and the position is fixed at the beginning. If you need case-insensitive prefix matching, regionMatches with ignoreCase=true is a better choice than converting both strings to lowercase, which creates extra objects and can have locale-related issues.

For example, to check a prefix without case sensitivity:

String input = "HelloWorld"; if (input.regionMatches(true, 0, "hello", 0, 5)) { System.out.println("Starts with hello (case-insensitive)"); }

The regionMatches method avoids allocating a lowercased copy of the input and gives you explicit control over the comparison region.

Performance Considerations

The startsWith method is implemented by comparing characters directly without creating intermediate strings. It runs in linear time proportional to the length of the prefix, and it does not compile or execute a regular expression. This makes it significantly faster than matches for simple prefix checks, especially when the prefix is short and the method is called frequently in a loop or a hot path.

There is no hidden cost from locale or encoding conversion because the comparison operates on the internal char array of the string. In practice, startsWith is one of the cheapest string operations available in the Java standard library.

One subtle performance point: when you use the offset variant, the method does not copy the substring; it simply starts the comparison at the given index. This is more efficient than calling substring(offset).startsWith(prefix), which would allocate a new string.

If you need to check multiple prefixes against the same string, consider using a Set of prefixes and a loop, but remember that startsWith still scans from the beginning each time. For a single string and many prefixes, a more sophisticated data structure like a trie may be warranted, but for typical use cases startsWith is sufficiently fast.

Common Pitfalls and Practical Guidance

A frequent mistake is assuming startsWith is case-insensitive. It is not. If your application requires case-insensitive prefix matching, use regionMatches or normalize both strings with toLowerCase(Locale.ROOT) before calling startsWith. The latter approach is simpler but creates extra strings, so it is better to use regionMatches in performance-sensitive code.

Another pitfall is using startsWith to validate file extensions. For example, "file.TXT".startsWith("file") returns true, but "file.TXT".endsWith(".txt") returns false because endsWith is also case-sensitive. Always consider the case sensitivity of the data you are validating.

The offset parameter can be confusing because it is zero-based and does not throw an exception for out-of-range values. If you rely on the offset to parse structured data, verify the offset bounds beforehand to avoid silent false results that may hide bugs.

Finally, remember that startsWith works on the exact String content. If you are dealing with StringBuilder or StringBuffer, you must call toString() first, which creates a new string. For frequent prefix checks on mutable text, consider keeping the data as a String when possible to avoid repeated conversions.

When you need to check a prefix at a fixed position that is not zero, the offset overload is the cleanest and most efficient option. It avoids substring allocation and keeps the intent clear. For all other cases, the single-argument version is the standard choice.

Understanding these details helps you use startsWith correctly and avoid the subtle bugs that arise from case sensitivity, null handling, and offset semantics. The method is simple, but its behavior is precise, and knowing those boundaries makes your code more robust.

java string startswith: Practical Usage and Code Examples | RYUSLOG DEV