In this tutorial, you will learn about String startsWith() method, its syntax, and usage with examples.
Java String startsWith() method
In Java, String startsWith() method takes a value (string type) as argument, and checks if the string starts with the given value
Syntax of startsWith()
The syntax to call String startsWith() method in Java is
string.startsWith(value)
startsWith() takes a single parameter.
Parameter | Description |
---|---|
value | [Mandatory] A String type value.The string value, representing the characters to check for, if the string starts with. |
startsWith() returns value of boolean type.
Examples
1. startsWith() – Check if the string starts with “Hel” in Java
In this example, we take a string value "Hello World"
in str and check if str starts with a value of "Hel"
using String startsWith() method.
Since the startsWith() method returns a boolean value, we can use the method call in the condition of Java If Else statement.
Java Program
public class Main {
public static void main(String[] args) {
String string = "Hello World";
if (string.startsWith("Hel")) {
System.out.println("The string STARTS with given value.");
} else {
System.out.println("The string DOES NOT START with given value.");
}
}
}
Output
The string STARTS with given value.
Since str starts with the prefix string “Hel”, the startsWith() method returns true, and the if-block is run.
2. startsWith() – The string does not start with specified prefix string
In this example, we take a string value "Hello World"
in str and check if str starts with a value of "Apple"
using String startsWith() method.
Java Program
public class Main {
public static void main(String[] args) {
String string = "Hello World";
if (string.startsWith("Apple")) {
System.out.println("The string STARTS with given value.");
} else {
System.out.println("The string DOES NOT START with given value.");
}
}
}
Output
The string DOES NOT START with given value.
Since the string value in str does not start with “Apple”, the startsWith() method returns false, and the else-block is run.
Conclusion
In this Java String Methods tutorial, we have seen about String startsWith() method in Java, its syntax, and how to use String startsWith() method in Java programs with the help of examples.