Java String.startsWith() method checks if a string begins with the specified prefix substring. The argument prefix must be a standard substring, the regular expressions are not supported.
1. String.startsWith() API
The startsWith() method is an overloaded method and has two forms:
- boolean startsWith(substring) – returns
true
if thesubstring
is a prefix of the String. - boolean startsWith(substring, fromIndex) – returns
true
if the String begins withsubstring
starting from the specified indexfromIndex
.
2. String.startsWith(substring) Example
The following Java program checks if a string starts with the specified prefixes.
String blogName = "howtodoinjava.com";
Assertions.assertTrue(blogName.startsWith("how"));
Assertions.assertTrue(blogName.startsWith("howto"));
Assertions.assertFalse(blogName.startsWith("hello"));
2.1. Regular Expressions are Not Supported
Note that the startsWith()
does not support regular expressions as an argument. If we pass the regex as an argument, it will only be treated as a normal string.
String blogName = "howtodoinjava.com";
Assertions.assertFalse(blogName.startsWith("^h"));
If you want to check the prefix with regular expressions, then you can use the Pattern and Matcher API.
2.2. Null is Not Allowed
Please note that null is not allowed as a method argument. The method will throw NullPointerException if null
is passed.
Assertions.assertThrows(NullPointerException.class, () -> {
blogName.startsWith(null);
});
3. String.startsWith(substring, fromIndex) Example
The startsWith(substring, fromIndex) also checks for substring prefix but the difference is that it checks the prefix beginning at the specified index position using fromIndex
.
This method also does not accept null
argument.
String blogName = "howtodoinjava.com";
Assertions.assertTrue(blogName.startsWith("h", 0));
Assertions.assertFalse(blogName.startsWith("do", 0));
Assertions.assertTrue(blogName.startsWith("do", 5));
Happy Learning !!
Reference: Java String Doc
Leave a Reply