Java String startsWith() method is used to check the prefix of string. It verifies if given string starts with argument string or not.
startsWith() method is overloaded method and has two forms:
- boolean startsWith(String str) – returns
true
if thestr
is a prefix of the String. - boolean startsWith(String str, int fromIndex) – returns
true
if the String begins withstr
starting from the specified indexfromIndex
.
1. String startsWith(String str) example
Java program to check if a string starts with prefix argument string.
public class StringExample { public static void main(String[] args) { String blogName = "howtodoinjava.com"; System.out.println( blogName.startsWith("how") ); //true System.out.println( "howtodoinjava.com".startsWith("howto") ); //true System.out.println( "howtodoinjava.com".startsWith("hello") ); //false } }
Program output.
true true false
String
startsWith()
method does not accept regular expression as argument. If we pass and regex pattern as argument, it will be treated as normal string only.
1.1. ‘null’ method argument is not allowed
Please note that null is not allowed as method argument. It will throw NullPointerException if null
is passed.
public class StringExample { public static void main(String[] args) { String blogName = "howtodoinjava.com"; blogName.startsWith(null); } }
Program output.
Exception in thread "main" java.lang.NullPointerException at java.lang.String.startsWith(String.java:1392) at java.lang.String.startsWith(String.java:1421) at com.StringExample.main(StringExample.java:9)
2. Java String startsWith(String str, int fromIndex) example
Similar to startsWith( str )
method, this also checks for prefix. The difference if that it checks the prefix str
beginning at the specified fromIndex
.
This method also does not accept null
argument to the method.
public class StringExample { public static void main(String[] args) { String blogName = "howtodoinjava.com"; System.out.println( blogName.startsWith("howto", 0) ); //true System.out.println( "howtodoinjava.com".startsWith("howto", 2) ); //false } }
Program output.
true false
Reference: