The startsWith() method of the Java String class checks whether a string begins with the specific characters or not. Developers are often required to filter the data for particular characters such as extracting the products that start with specific strings or characters, etc. Instead of manually writing code for this functionality, the users can call the startsWith() method in Java from the java.lang package.
This article demonstrates the implementation and usage of the startsWith() Method in Java.
How to Use Java String StartsWith() Method?
The startsWith() method falls under the category of static function and hence, can be called directly using the String class. It takes two parameters that are prefix and offset. The “prefix” is a required parameter while the “offset” is optional. It returns the boolean output i.e., true or false.
Syntax
To determine if a string begins with specific characters, the following basic syntax is used:
public boolean startsWith(String prefix)
In the syntax mentioned above:
- The “prefix” parameter is of string data type. It accepts the sequence of characters that is to be matched with the string.
On the other hand, if the user wants to test if the string contains specific characters at a particular index, the syntax given below is used:
public boolean startsWith(String prefix , int toffset)
Within the above-given syntax:
- The toffset accepts an integer value and determines whether the string matches the prefix from the given index to onwards.
Another variant for the startsWith() method is given below. This syntax checks the sequence of characters from the starting index to the ending index:
public boolean startsWith(String prefix, int toffset, int offset)
In this syntax: (to be checked)
- The toffset refers to the index from where the comparison of the prefix with the string should start.
- The offset represents the index till where the comparison of the prefix with the string should be.
Let’s explore various examples to understand the startsWith() method functionality.
Example 1: Determine Whether the String Starts With the Specific Character or Not
The example given below determines the existence of a specific character at the beginning of the string:
public class StartsWith {
public static void main(String[] args) {
String check_str="JavaBeat";
System.out.println("The result is " + check_str.startsWith("J"));
}
}
In the above-mentioned code:
- A string “check_str” is declared and initialized with the “JavaBeat” value in the main() method.
- The “System.out.println()” prints the output. The “check_str” variable directly calls the startsWith() method which checks if the string begins with the character “J” or not.
Output
The string “JavaBeat” begins with the character “J” and hence, the output returned is true as shown below:
Example 2: Determine Whether the StartsWith() Method is Case Sensitive or Not
Java is a case-sensitive programming language that behaves differently for uppercase and lowercase letters. Therefore, despite the exact spellings, the strings “JavaBeat” and “javabeat” are not the same in Java due to case sensitivity.
In this example, the string “check_str” is initialized with the “JavaBeat” value in the main() method. The print statement is used to display the output:
public class StartsWith {
public static void main(String[] args) {
String check_str="JavaBeat";
System.out.println("The result is " + check_str.startsWith("j"));
}
}
Output
The result returned by the startsWith() method is false which indicates that it is case-sensitive:
Example 3: Determine if a String Starts With Specific Characters or Not in the User Input
Aside from using the initialized value for a string, the startsWith() function can also be used on the user input as shown in this example:
import java.util.Scanner;// includes the Scanner class of the package
public class StartsWith {
public static void main(String[] args) {
Scanner input=new Scanner(System.in); //Scanner object is created from the Scanner class
System.out.println("Enter a String");
String myString=input.next();
System.out.println("Enter the prefix");
String prefix=input.next();
System.out.println("The result is " + mystring.startsWith(prefix));
}
}
In the code mentioned above:
- The import java.util.* statement imports all the necessary classes and functions for this code such as Scanner.
- The “input” object is declared using the new keyword of the Scanner class. The “System.in” in the Scanner class specifies that the input is to be entered from the keyboard (Standard input).
- The print statement prompts the user for a string. This entered string is stored in the myString variable and will be checked for the prefix by the startsWith() method.
- The second print statement is used for taking the prefix as input. The prefix contains characters that are to be checked with the string. The next() function of the Scanner class is used for taking the input.
- In the last print statement, the “startsWith()” method is called using the “myString” variable. Within this method, the prefix variable is passed to check if “myString” contains the characters specified in the prefix.
Output
Example 4: Determine a String That Starts With Specific Characters Within an Array
In Java, arrays contain data that is of the same data type. The startsWith() method of Java can be used to determine if the elements at each index within the array begin with specific characters or not. The code is given as follows:
import java.util.Scanner;// includes the Scanner class of the package
public class StartsWith // the public class that contains the main method
{
public static void main(String[] args) // main method that uses the startsWith() function
{
String[] fruits= {"Mango", "Apple", "Orange"};
for (int i=0;i<fruits.length;i++)
{
String check=fruits[i];
System.out.println("The results is " + check.startsWith("M"));
}
}
}
Within the above-mentioned code:
- An array of string datatype named “fruits” is declared and initialized.
- The for loop iterates over every index of the “fruits” array. An integer-type variable “i” is initialized with the value “0” inside the for loop. In each iteration, the condition “i< fruits.length” is checked. Similarly, the value of “i” is also incremented. The loop terminates when the value of “i” exceeds the array’s length.
- Within the for loop, a string variable “check” is declared and initialized. It will store the value at the current index of the fruit array.
- A print statement is used to check whether the element at the index begins with the character “M” or not and displays a boolean output.
Output
Example 5: Determine if the String Contains Specific Characters Using Offset
The offset parameter is optional and determines if the string at a particular index begins with the mentioned characters. By default, the index for offset is zero if no value is provided. Given below image shows the indexing of the string:
The startsWith() method will match the prefix “Beat” with the string “JavaBeat” from index 4 onwards. The example is given as follows:
public class StartsWith // the public class that contains the main method
{
public static void main(String[] args) // main method that uses the startsWith() function
{
String myString="JavaBeat";// a string is declared and initialized
System.out.println("The result is " + myString.startsWith("Beat",4));
}
}
Within the above-mentioned code:
- In the main function, the string “myString” is declared and initialized using the “JavaBeat” value.
- The startsWith() method is invoked using the “mystring” variable within the print statement. Inside this method, the prefix that is to be matched with the string starts from the 4th index.
Output
In the output window, the result returned is true as shown below:
Note: The startsWith() method will return false for the out-of-index values for a string.
Example 6: Determines if a Line Starts With Specific Characters Within a File
The startsWith() method in Java can also be used with files.The startWith() function iterates over each line using the for loop to check if the beginning of each line in a file matches the specified characters or not. The code is given as follows:
import java.nio.file.*;
import java.io.*;
import java.util.*;
public class StartsWith {
public static void main(String[] args) { // the main function that contains the code for execution
String filepath=<FilePath>;
Path path = Paths.get(filepath);
try {
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
System.out.println("the result for the line "+ "\"" + line + "\"" + " " +line.startsWith("This"));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note: While providing the file path, use a double-slash within the path as a single slash results in exceptions e.g., “C://Users//%FileName%”.
Within this code:
- The “import java.nio.file.*” statement imports all the classes, and functions to work with the files. This class involves static methods that work with files via the Path object.
- Similarly, the “import java.io.*” statement imports functions and classes to perform I/O operations on files.
- The “import java.util.*” includes different methods and classes for taking input and managing List.
- In the main() method, a string-type variable “filepath” is declared. Replace the placeholder “<FilePath>” with your file’s path to read a specific file.
- A path object is created using the Path.get() method. The “filepath” variable within this method is used for reading the directory’s path.
- Working with files results in exceptions oftentimes. Therefore, a List of string data type names “lines” is declared within the try block. The “Files.readAllLines()” method reads all the lines within the file. The path parameter is passed to it for reading a specific file.
- Next, a for loop that iterates over each line of the file . A string variable “line” is declared that reads all the data from the “lines” list.
- For each line, the startsWith() method checks whether a particular line starts with specific characters or not and prints the output.
- The catch block will throw an IOException in case of an error. The “e” object is used to print the stack trace.
Output
Example 7: Determines if a Substring Starts With Specific Characters via the Starting and Ending Index
The startsWith() method in Java also inputs the starting and the ending index to test a substring for specific characters. The string will only be checked within the specified index limit and the result will be returned. To implement this functionality, the code is given as follows:
public class StartsWith {
public static void main(String[] args) {
String check_str = "JavaBeat";
String substring = check_str.substring(0, 4);
System.out.println("The result is " + substring.startsWith("Java"));
}
}
In the above-mentioned code:
- The string variable “check_str” is declared and initialized with the value “JavaBeat”.
- The substring() method will slice the characters from the 0th index to the 4th index i.e., “Java” and store the value in the “substring” variable.
- Within the print statement, the startsWith() method is called using the substring variable. It will check whether the string in the substring variable begins with the specified prefix.
Output
What are the Common Exceptions in the startsWith() Method of Java String Class?
The two most common exceptions while using the startsWith() method in Java are NullPointerException and IndexOutofBound Exception. They are discussed as follows:
Exception 1: NullPointerException
The NullPointerException occurs when the prefix of the startsWith() method is null or the string that is to be checked is null as shown below:
Solution: To resolve this error, ensure that the string or the prefix contains a string value or empty spaces. The empty spaces do not result in the Null pointer exception
Exception 2: IndexOutofBoundException
This exception occurs when the user is trying to access an index that exceeds the limit of the array. Thus, no such index exists which results in the “IndexOutofBoundsException”:
Solution: To resolve this error, ensure that the loop variable starts from 0 and is less than the length of the array. This will terminate the loop when the loop variable exceeds the length of the array and prevents the exception, as shown below:
Conclusion
The Java String class startsWith() method tests if a string starts with specific characters and returns a boolean output as shown in the mentioned examples. There are three different signatures of this method that are used interchangeably. The Java developers can directly call the startsWith() method from the String class. This write-up is a step-by-step guide for the implementation of the Java String class startsWith() method.