Java String startsWith() example

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:

  1. boolean startsWith(String str) – returns true if the str is a prefix of the String.
  2. boolean startsWith(String str, int fromIndex) – returns true if the String begins with str starting from the specified index fromIndex.

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:

Java String Doc

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.