Java.lang.String.startsWith() Method



Description

The java.lang.String.startsWith(String prefix, int toffset) method tests if the substring of this string beginning at the specified index starts with the specified prefix.

Declaration

Following is the declaration for java.lang.String.startsWith() method

public boolean startsWith(String prefix, int toffset)

Parameters

  • prefix − This is the value of prefix.

  • toffset − This is where to begin looking in this string.

Return Value

This method returns true if the character sequence represented by the argument is a prefix of the substring of this object starting at index toffset, else false.

Exception

NA

Example

The following example shows the usage of java.lang.String.startsWith() method.

package com.tutorialspoint;

import java.lang.*;

public class StringDemo {

   public static void main(String[] args) {

      String str = "www.tutorialspoint.com";
      System.out.println(str);

      // the start string to be checked
      String startstr1 = "tutorialspoint";
      String startstr2 = "tutorialspoint";

      // checks that string starts with given substring and starting index
      boolean retval1 = str.startsWith(startstr1);
      boolean retval2 = str.startsWith(startstr2, 4);

      // prints true if the string starts with given substring
      System.out.println("starts with " + startstr1 + " ? " + retval1);
      System.out.println("string " + startstr2 + " starting from index 4 ? "
         + retval2);
   }
}

Let us compile and run the above program, this will produce the following result −

www.tutorialspoint.com
starts with tutorialspoint ? false
string tutorialspoint starting from index 4 ? true
java_lang_string.htm
Advertisements