Java String startsWith() Method

      No Comments on Java String startsWith() Method




Java String startsWith() method is used to check whether a String starts with a given prefix if no index is specified or if String starts with a given prefix at the specified index.

Variants of startsWith() Method

There are two variants of startsWith() method of String in Java.

(I.) boolean startsWith(String prefix)

This method checks whether a String starts with the given prefix or not.
e.g.

String str = “HelloWorld”;
boolean flag = str.startsWith(“He”); // true
boolean flag = str.startsWith(“ell”); // false

Here, “HelloWorld” starts with “He” and not “ell” as no offset/index is specified and hence it is checked from beginning.

(II.)boolean startsWith(String prefix, int toffset)
This method checks whether a String starts with the given prefix from the specified index/offset or not.

e.g.

String str = “HelloWorld”;
boolean flag = str.startsWith(“He”,0); // true
boolean flag = str.startsWith(“He”,1); // false
boolean flag = str.startsWith(“ell”,1); // true

“HelloWorld” starts with “He” at index 0 and hence true.
“HelloWorld” does not starts with “He” at index 1 and hence false.
“HelloWorld” starts with “ell” at index 1 and hence true.

NOTE: Index / offset starts with 0 .

Let’s take an example to understand this.

Example : Java String startsWith() Method

package com.masterjavatutorial;
public class Test {
	public static void main(String[] args) {
		
		String str="HelloWorld";
		
		boolean startsWith = str.startsWith("He"); 
		System.out.println(startsWith); 

		startsWith = str.startsWith("He",1); 
		System.out.println(startsWith); 

		startsWith = str.startsWith("ell",1); 
		System.out.println(startsWith); 

		startsWith = str.startsWith("orl",6); 
		System.out.println(startsWith); 

	}
}

Output of the above program is as below:

true
false
true
true