BlogsDope image BlogsDope

Java String startsWith() Method

March 16, 2021 JAVA FUNCTION STRING 620

The Java startsWith() method is a case-sensitive method used to check whether a input string starting with a user-specified string or not. In addition to it we can also define the starting index of the string.

Java startsWith() Example

  • Input: "Welcome to Codesdope".startsWith("Welcome")

       Output: true      //"welcome" is the first word of the input string.

  • Input: "Welcome to Codesdope".startsWith("to")

       Output: false     //"to" is not the starting word of the input string.

Java startsWith() Syntax

String.startsWith(String prefix)
String.startsWith(String prefix, int starting_index)

JAVA startsWith() Parameters

prefix-string - that you want to search in sentence 

starting_index - the index position from where you want to search the prefix in the string.

JAVA startsWith() Return

This method returns a boolean value-

Returns true if the string starts with the given prefix.

Returns false if the string doesn't start with the given prefix.

Java startsWith() Program

package codesdope;
import java.util.*;
public class codesdope 
{
	public static void main(String[] args) 
       {
		String s1="Codesdope";
		System.out.println(s1.startsWith("Code"));         //case-1
		System.out.println(s1.startsWith("ode"));          //case-2
		System.out.println(s1.startsWith("code"));         //case-3
		System.out.println(s1.startsWith("ode",1));        //case-4
	}
}

​true 

false 

false 

true

  • In the first case, we are finding whether our string s1 i.e "Codesdope" is starting with the "Code" or not using startsWith method and it returned true because "Codesdope" starting four characters are "Code".
  • In the second case, we are finding whether our string s1 i.e. "Codesdope" is starting with the "ode" or not using startsWith  method and it returned false because "Codesdope" starts with characters "C" not "o".
  • In the third case, we are finding whether our string s1 i.e "Codesdope" is starting with the "code" or not using startsWith method and it returned false because "Codesdope" starts with upper-case character  "C" not with lower-case.
  • In the last case, we are finding whether our string s1 i.e "Codesdope" is starting with the "ode" or not using startsWith method with the given index position 1 and it returned true because in the string "Codesdope"  when we start viewing it from index position 1 then it starts with "ode".

Liked the post?
Editor's Picks
0 COMMENT

Please login to view or add comment(s).