Java String startsWith()

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 the substring is a prefix of the String.
  • boolean startsWith(substring, fromIndex) – returns true if the String begins with substring starting from the specified index fromIndex.

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

Sourcecode on Github

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial