14 May String startsWith(String prefix) method in Java
The startsWith(String prefix) method in Java tests if this string starts with the specified prefix.
Syntax
Let us see the syntax,
boolean startsWith(String prefix)
Parameters
Let us see the parameters,
- prefix − prefix to be matched
Example 1
The following is an example of boolean startsWith(String prefix),
public class StudyopediaDemo {
public static void main(String args[]) {
String message = new String("Studyopedia provides free learning content!");
System.out.println("String: "+message);
System.out.print("Result= " );
System.out.println(message.startsWith("learning"));
System.out.print("Result= " );
System.out.println(message.startsWith("content"));
System.out.print("Result= " );
System.out.println(message.startsWith("Studyopedia"));
System.out.print("Result= " );
System.out.println(message.startsWith("Study"));
}
}
Output
The following is the output,

Example 2
Here, let us take the substring from the user using the Scanner class:
// Check if a string starts with the specified prefix in Java (take the substring from user input)
import java.util.Scanner;
class Demo62 {
static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String message = "Never Stop Learning";
System.out.print("Enter the substring = ");
String subString = sc.nextLine().trim(); // trim removes leading/trailing spaces
if (subString.isEmpty()) {
System.out.println("You did not enter any substring!");
} else {
System.out.println("Does the string start with the specific substring? = " +
message.startsWith(subString));
}
}
}
Output
Enter the substring = Nev Does the string starts with a specific substring = true
No Comments