Java String startsWith() Method with Examples (original) (raw)
Last Updated : 22 Nov, 2024
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 thejava.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 `
// 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);
}
}
`
Table of Content
Syntax of startsWith() method
boolean startsWith(String prefix)
- **Parameter: prefix: The prefix to be checked.
- *Return Types:
It returns
true
,
if the string starts with the specified prefix, otherwise*false
**.
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 `
// 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);
}
}
`
**2. Check with a Different Prefix
We can use startsWith() method to check if the string starts with any other prefix.
**Example:
Java `
// 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);
}
}
`
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 `
// 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);
}
}
`