Java – Check if this String Starts with a String

To check if this String starts with a string, you can use String.startsWith() function, or you can use some other ways.

In this tutorial, we will go through different processes to know some of the possible ways of checking if this string starts with a specific string.

First we shall see the standard way of using String.startsWith() function.

The syntax of startsWith() function is as follows.

</>
Copy
 String.startsWith(String str)

startsWith() function checks if this string starts with the string passed as argument to the function.

Following are some of the quick examples of String.startsWith() method.

</>
Copy
"tutorialkart".startsWith("tutorial"); //true
"tutorialkart".startsWith("kart"); //false
"tutorialkart".startsWith("tut"); //true
"tutorialkart".startsWith("al"); //false

Let us dive into some Java programs that demonstrate different ways to check if this string starts with a string.

1. Example – Check If string starts with a specific value in Java

In this example, we have taken two strings: str1 and str2. After that we shall check if str1 starts with str2 using String.startsWith() method.

CheckIfStringStartsWith.java

</>
Copy
/**
 * Java Example Program to Check if String starts with
 */

public class CheckIfStringStartsWith {

	public static void main(String[] args) {
		String str1 = "www.tutorialkart.com";
		String str2 = "www";
		
		boolean b = str1.startsWith(str2);
		System.out.print(b);
	}
}

Run the above program and you should get the following output in console.

Output

true

2. Example – Check if given website starts with “www” in Java

In this example, we have written a custom function, to check if a string starts with the specified string.

CheckIfStringStartsWith.java

</>
Copy
/**
 * Java Example Program to Check if String starts with
 */

public class CheckIfStringStartsWith {

	public static void main(String[] args) {
		System.out.println(ifStartsWith("www.tutorialkart.com", "www"));
	}
	
	/**
	 * Checks if str1 starts with str2
	 * @param str1
	 * @param str2
	 * @return return true if str1 starts with str2, else return false
	 */
	public static boolean ifStartsWith(String str1, String str2) {
		if(str1.length()>=str2.length()) {
			if(str1.substring(0, str2.length()).equals(str2)) {
				return true;
			}
		}
		return false;
	}
}

Run the program.

Output

true

Conclusion

In this Java Tutorial, we learned how to check if a String starts with another string.