How to check if the string begins with specific substring in Java?



A String class can be used to represent the character strings, all the string literals in a Java program are implemented as an instance of a String class. The Strings are constants and their values cannot be changed (immutable) once created.

We can use the startsWith() method of String class to check whether a string begins with a specific string or not, it returns a boolean, true or false.

Syntax

public boolean startsWith(String prefix)

Example

Open Compiler
public class StringStartsWithSubStringTest { public static void main(String[] args) { String str = "WelcomeToTutorialsPoint"; if(str.startsWith("Welcome")) { System.out.println("Begins with the specified word!"); } else { System.out.println("Does not begin with the specified word!"); } } }

Output

Begins with the specified word!
Updated on: 2023-12-01T14:34:36+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements