Java string startsWith()
Java string startsWith()
method is used to check if a string begins with some string. In other words, it is also used to check if a string starts with a prefix.
As per java docs,
Tests if this string starts with the specified prefix
startsWith()
accepts a string argument. It returns true
if the string on which it is called begins with the argument string. In other words, it returns true, if the starting characters of the string are the same as the argument string.
startWith()
returns false
, if all the characters of the argument string does not match with the starting characters of the string on which it is called.
startsWith() overloads
There are two overloaded versions of startWith()
in string class.
1. startsWith(String)
Checks if the string starts with the argument string. Returns true
or false
.
2. startsWith(String, int)
Checks if the caller string starts with argument string beginning from the specified index.
Both versions of startWith()
performs a case sensitive comparison
String startsWith() example
Below is an example of java string startsWith()
method.
String s = "test123"; System.out.println(s.startsWith("test")); // true System.out.println(s.startsWith("tests")); // false // case sensitive check System.out.println(s.startsWith("Test")); // false // startswith index System.out.println(s.startsWith("123",4)); // true System.out.println(s.startsWith("123",0)); // false // regex check System.out.println(s.startsWith("t*")); // false
Above examples make it clear that startsWith()
performs case sensitive comparison and it does not work with regular expression(regex).
If we supply null to
startsWith()
, then it will throw a NullPointerException. That is, String s = "test123"; System.out.println(s.startsWith(null));
Output will be
Exception in thread “main” java.lang.NullPointerException: Cannot invoke “String.length()” because “prefix” is null
at java.base/java.lang.String.startsWith(String.java:1457)
at java.base/java.lang.String.startsWith(String.java:1500)
at com.codippa.ExceptionHandlingDemo.main(ExceptionHandlingDemo.java:7)
This is because internally startsWith()
performs a length check over the argument by calling string.length() method on it. And calling a method on null results in NPE.
String startsWith() on empty string
Every string begins with an empty string by default. So, calling startsWith()
with empty string argument will always return true
. Example,
String s = "test123"; System.out.println(s.startsWith("")); // true
This is because a string "test123"
can be written as "" + "test123"
.