In Java, the startsWith() method of the String class is used to check if a string starts with the given prefix. The startsWith() method is present in the java.lang package. In this article, we will learn how to use the startsWith() method in Java.
Example:
In the below example, we will use the startsWith() method to check if the string starts with a given prefix.
// Java program to demonstrate startsWith() method
public class StringStartsWith {
public static void main(String[] args) {
// Declare and initialize a String
String s = "Java Programming";
// Check if the string starts with "Java"
boolean r = s.startsWith("Java");
System.out.println("" + r);
}
}
Output
true
Table of Content
Syntax of startsWith() method
boolean startsWith(String prefix)
- Parameter: prefix: The prefix to be checked.
- Return Types:
It returnstrue,if the string starts with the specified prefix, otherwisefalse.
Other Examples of startsWith() Method
1. Check with Case Sensitivity
The startsWith() method is case-sensitive. This means it will return false if the case of the characters does not match.
Example:
// Java program to demonstrate case sensitivity of startsWith()
public class StringStartsWith {
public static void main(String[] args) {
// Declare and initialize a String
String s = "Java Programming";
// Check if the string starts with "java" (lowercase)
boolean r = s.startsWith("java");
System.out.println("" + r);
}
}
Output
false
2. Check with a Different Prefix
We can use startsWith() method to check if the string starts with any other prefix.
Example:
// Java program to demonstrate startsWith() with a different prefix
public class StringStartsWith {
public static void main(String[] args) {
// Declare and initialize a String
String s = "Java Programming";
// Check if the string starts with "Java"
boolean r = s.startsWith("Java");
System.out.println("" + r);
}
}
Output
true
3. Using startsWith() with Index
We can also specify an index in the startsWith() method. It checks whether the substring starting from that index begins with the specified prefix.
Example:
// Java program to demonstrate startsWith() with index
public class StringStartsWith {
public static void main(String[] args) {
// Declare and initialize a String
String s = "Java Programming";
// Check if the string starting from index 5 starts with "Pro"
boolean r = s.startsWith("Pro", 5);
System.out.println("" + r);
}
}
Output
true