The startsWith() method of String class is used for checking prefix of a String. It returns a boolean value true or false based on whether the given string begins with the specified letter or word.
For example:
String str = "Hello"; //This will return true because string str starts with "He" str.startsWith("He");
Java String startsWith() method
There are two variations of starsWith() method.
boolean startsWith(String str)
: It returns true if the String str is a prefix of the String.
boolean startsWith(String str, index fromIndex)
: It returns true if the String begins with str, it starts looking from the specified index “fromIndex”. For example lets say that the value of the String s is “Hi there” and we are calling starsWith() method like this – s.startsWith(“there”, 3) then this will return true because we have passed value 3 as fromIndex, the searching of keyword “there” begins from the index 3 of the given string s and it is found at the beginning of the string s.
A simple example of startsWith() method
This is a simple example where we have a string s and we are checking wether the string s starts with a particular word using startsWith() method.
public class JavaExample{ public static void main(String args[]){ //given string String s = "This is just a sample string"; //checking whether the given string starts with "This" System.out.println(s.startsWith("This")); //checking whether the given string starts with "Hi" System.out.println(s.startsWith("Hi")); } }
Output:
Java String startsWith() method example
Lets take an example where we are using both the variations of startsWith() method.
public class StartsWithExample{ public static void main(String args[]) { String str= new String("quick brown fox jumps over the lazy dog"); System.out.println("String str starts with quick: "+str.startsWith("quick")); System.out.println("String str starts with brown: "+str.startsWith("brown")); System.out.println("substring of str(starting from 6th index) has brown prefix: " +str.startsWith("brown", 6)); System.out.println("substring of str(starting from 6th index) has quick prefix: " +str.startsWith("quick", 6)); } }
Output:
String str starts with quick: true String str starts with brown: false substring of str(starting from 6th index) has brown prefix: true substring of str(starting from 6th index) has quick prefix: false
will startsWith method return true if the input is:
search string-aab
list-{bcf , nhgggg , aabde}
As per my knowledge it should return true as aabde contains aab.
Am i right?
Will it check starting word or starting letter…??
It depends on what you are passing in the startsWith() method, for example if you are calling the method like this: str.startsWith(“A”) then it will check whether the string str starts with letter ‘A’ or not.