STRING INSTANCE METHODS
Java String startsWith() method
startsWith() checks whether a string begins with a supplied character sequence: a prefix. It returns true or false. You can also check from a chosen index. The original string is unchanged.
Checking the start of a string
String tekstas = "JavaQuest";
System.out.println(tekstas.startsWith("Java"));
System.out.println(tekstas.startsWith("Quest"));true
false
tekstasstores the value JavaQuest.startsWith("Java")compares the first four characters with the supplied prefix. They match, so the result istrue.- Quest occurs in the string, but not at its beginning. The second call therefore returns
false. - A prefix is the character sequence checked at the beginning. The method does not search for it elsewhere in the string.
Calling startsWith() and saving the result
startsWith() is an instance method: call it on the string being checked. Pass the expected beginning as the argument for the parameter prefix.
String tekstas = "Java";
boolean sutampa = tekstas.startsWith("Ja");
System.out.println(sutampa);
System.out.println(tekstas.startsWith("Java"));
System.out.println(tekstas.startsWith("JavaQuest"));
System.out.println(tekstas);true
true
false
Java
A shorter prefix can match, and the whole string is also its own prefix. A longer prefix does not fit and returns false.
Store the result in a variable of type boolean. The last line shows that the original string is unchanged. This is not a static call on the class name.
Method syntax: two overloads
public boolean startsWith(String prefix)
public boolean startsWith(String prefix, int toffset)
| Part | Meaning |
|---|---|
prefix | String โ the whole character sequence that must match from the chosen position. It is not a regex. |
toffset | int โ the starting index in the string being checked. Indexes start at zero and count UTF-16 units. |
| Return type | boolean |
true | The whole prefix matches from the position being checked. |
false | The prefix does not match or does not fit from the specified position. |
The one-argument overload starts at index 0. Both overloads distinguish uppercase and lowercase. The second argument is a starting position, not an end index or comparison length.
Uppercase and lowercase are different
String tekstas = "JavaQuest";
System.out.println(tekstas.startsWith("java"));
System.out.println(tekstas.startsWith("JAVA"));
System.out.println(tekstas.startsWith("Java"));false
false
true
Java, java and JAVA are different character sequences. Case must match throughout the supplied prefix, not only in its first letter.
Checking from a specific index
String tekstas = "ID: JavaQuest";
System.out.println(tekstas.startsWith("Java", 4));
System.out.println(tekstas.startsWith("Quest", 4));
System.out.println(tekstas.startsWith("Quest", 8));
System.out.println(tekstas.startsWith("Java", 0));true
false
true
false
| The index | Character |
|---|---|
0 | I |
1 | D |
2 | : |
3 | Space |
4 | J |
8 | Q |
- From index
4the string starts with JavaQuest, so the prefix Java matches. startsWith("Quest", 4)does not skip to a later word: at index4the character is J, rather than Q.startsWith("Quest", 8)matches because the starting position is now correct.- Index
0checks the beginning of the whole string, so Java does not match there.
The table lists only the positions needed for this explanation; the omitted indexes still exist.
Bounds: when is the result false?
String tekstas = "Java";
System.out.println(tekstas.startsWith("Ja", -1));
System.out.println(tekstas.startsWith("Ja", 5));
System.out.println(tekstas.startsWith("Java", 1));
System.out.println(tekstas.startsWith("a", 3));
System.out.println(tekstas.startsWith("J", 4));false
false
false
true
false
All prefixes are non-null in this example. A negative index or one beyond the string length returns false, rather than IndexOutOfBoundsException.
startsWith("Java", 1) also returns false: from index 1 only three characters remain, while the prefix needs four. The final single character a at index 3 still fits.
At an index equal to length(), there is no room even for one character of a non-empty prefix. Empty prefixes are covered separately.
A prefix is literal text, not a regex
String tekstas = "Java.Quest";
System.out.println(tekstas.startsWith("Java."));
System.out.println(tekstas.startsWith("Java.*"));
System.out.println(tekstas.startsWith("^Java"));
System.out.println("JavaQuest".startsWith("Java."));true
false
false
false
The dot . means a literal dot here. The characters * and ^ do not become special search instructions either. The method requires the exact supplied character sequence.
Checking a prefix without case sensitivity
String tekstas = "JAVAQuest";
String prefiksas = "java";
System.out.println(tekstas.startsWith(prefiksas));
System.out.println(tekstas.regionMatches(true, 0, prefiksas, 0, prefiksas.length()));
System.out.println(tekstas);false
true
JAVAQuest
startsWith() has no parameter for ignoring case. For this check, use regionMatches(true, 0, prefiksas, 0, prefiksas.length()).
The first argument enables case-insensitive comparison, both zeros select the starts of the strings, and the comparison length comes from the prefix. The original string is unchanged.
This does not apply language-specific collation rules. More about the method parameters: regionMatches().
Practical example: a command prefix and its space
String komanda = "run Main.java";
String prefiksas = "run ";
if (komanda.startsWith(prefiksas)) {
String failas = komanda.substring(prefiksas.length());
System.out.println(failas);
}
System.out.println("runner Main.java".startsWith("run"));
System.out.println("runner Main.java".startsWith(prefiksas));Main.java
true
false
startsWith(prefiksas)returnsboolean, so it can be used directly in anifcondition.- The prefix
"run "includes the space. This convention separates the command name from its following argument. substring(prefiksas.length())takes the text after the prefix. ThestartsWith()call itself only checks the beginning and removes no text.- runner Main.java starts with the letters run, but not with the sequence including the space. That is why the last two results differ.
This example checks an agreed command prefix. The remainder is printed as-is; its format and whether the file exists are not checked here.
Leading spaces are significant
String tekstas = " Java";
System.out.println(tekstas.startsWith("Java"));
System.out.println(tekstas.startsWith(" "));
System.out.println(tekstas.trim().startsWith("Java"));
System.out.println("[" + tekstas + "]");false
true
true
[ Java]
The first character is a space, so the string does not start with J. The method does not skip spaces automatically. If the task allows removing them, use the result of trim() for the prefix check. The original string still contains the space, as the last line shows.
An empty prefix and an empty string
System.out.println("Java".startsWith(""));
System.out.println("".startsWith(""));
System.out.println("".startsWith("J"));true
true
false
Every string, including an empty one, starts with the empty sequence "". An empty string cannot start with a non-empty sequence.
String tekstas = "Java";
System.out.println(tekstas.startsWith("", 2));
System.out.println(tekstas.startsWith("", tekstas.length()));
System.out.println(tekstas.startsWith("", 5));
System.out.println(tekstas.startsWith("", -1));
System.out.println(tekstas.startsWith("J", tekstas.length()));true
true
false
false
false
For an empty prefix, every index from 0 through tekstas.length() inclusive is valid. An index outside those bounds still returns false. The last call shows that the same end position does not work for a non-empty prefix.
If your application requires a non-empty prefix, also check !prefiksas.isEmpty(). That is an additional application rule, not a requirement of this method.
UTF-16 indexes: an emoji occupying two positions
String tekstas = "๐Java";
System.out.println(tekstas.length());
System.out.println(tekstas.startsWith("Java", 2));
System.out.println(tekstas.startsWith("Java", 1));
System.out.println(tekstas.startsWith("๐"));6
true
false
true
The emoji in this example ๐ occupies two UTF-16 char units. The string length is therefore six, and Java starts at index 2, not 1.
The last call shows that the emoji itself can be supplied as a prefix. An index is not the same as a count of user-perceived characters.
startsWith(), contains(), endsWith(), equals() and indexOf()
String tekstas = "JavaQuest.java";
System.out.println(tekstas.startsWith("Java"));
System.out.println(tekstas.startsWith("Quest"));
System.out.println(tekstas.contains("Quest"));
System.out.println(tekstas.endsWith(".java"));
System.out.println(tekstas.equals("Java"));
System.out.println(tekstas.indexOf("Quest"));true
false
true
true
false
4
| The method | Purpose |
|---|---|
startsWith() | Checks the beginning or one specified position. |
contains() | Looks for a character sequence anywhere in the string. |
endsWith() | Checks the final characters. |
equals() | Compares the whole string rather than just a prefix. |
indexOf() | Returns the index of the first match, or -1. |
In this string, Quest starts at index 4, so a search finds it while a check at the start of the whole string does not match.
contains() ยท endsWith() ยท equals() ยท indexOf()
A null prefix and a null receiver
String tekstas = "JavaQuest";
String prefiksas = null;
System.out.println(tekstas.startsWith(prefiksas));NullPointerException
The input string exists, but the prefix reference is null. This call throws NullPointerException. This is different from an empty prefix.
String tekstas = null;
System.out.println(tekstas.startsWith("Java"));NullPointerException
This time there is no object on which to call the method. The result is again an exception rather than false.
String tekstas = null;
String prefiksas = "Java";
boolean sutampa = tekstas != null
&& prefiksas != null
&& tekstas.startsWith(prefiksas);
System.out.println(sutampa);false
Check both references before calling the method. The operator && does not evaluate the rest of the condition once an earlier part is false. In this example the method is never called.
Common mistakes
- Expecting the method to find a prefix farther along the string.
toffsetis treated as an end index or a character count.- Forgetting that case and leading spaces must match.
- Using regex characters in the prefix and expecting pattern matching.
- Confusing an empty prefix with
null. - Counting the emoji in this example as one index position.
- Assuming that checking the beginning also removes the prefix or validates the rest of the input.
When should you use startsWith()?
Choose startsWith() when you need a clear answer about an agreed beginning: a command name, a code prefix or a fixed record marker. Use the offset overload when the starting position is already known.
For a match anywhere in the string, use contains() or indexOf(). To ignore case in the part being checked, use regionMatches().