Java – Check if a String Starts with Specified Prefix

To check if a String str starts with a specific prefix string prefix in Java, use String.startsWith() method. Call startsWith() method on the string str and pass the prefix string prefix as argument. If str starts with the prefix string prefix, then startsWith() method returns true.

Java Program

</>
Copy
public class Example {
	public static void main(String[] args) {
		String str = "apple";
		String prefix = "app";
		boolean result = str.startsWith(prefix);
		System.out.println("Does str start with specified suffix? " + result);
	}
}

Output

Does str start with specified suffix? true

If str does not start with the prefix string prefix, then startsWith() method returns false.

Java Program

</>
Copy
public class Example {
	public static void main(String[] args) {
		String str = "apple";
		String prefix = "mm";
		boolean result = str.startsWith(prefix);
		System.out.println("Does str start with specified suffix? " + result);
	}
}

Output

Does str start with specified suffix? false

Conclusion

In this Java Tutorial, we learned how to check if a string starts with a specified prefix string in Java.