startsWith() String Example

The String class comes with many helper methods with which Java string manipulation becomes easier. Forget the laborious days of C/C++. One such utility method is startsWith() String.

The present method startsWith(String str) checks the given string starts with a few characters like str or not. If starts with characters str, the method returns true else false.

startsWith() is overloaded 2 times. The signatures are given hereunder as defined in String class.

  1. public boolean startsWith(String str): Returns true if the given string starts with str, else false.
  2. public boolean startsWith(String str, int indexNumber): Returns true if the given string starts with str at index number indexNumber in the given string. That is, the previous method, checks at index number 0.

Following example illustrates the usage of both the above methods.

public class StringMethodDemo
{
 public static void main(String args[])
 {
  String str1 = "RajaRamMohan";
    
  boolean b1 = str1.startsWith("Raja");            // startsWith() String usage
  boolean b2 = str1.startsWith("Ram", 4);                 

  System.out.println(str1 +" starts with Raja: " + b1);
  System.out.println(str1 +" starts with Ram at index number 4: " + b2);

			                           // one practical example
			                           // to separate all the names starting with letter S
  String names[] = { "SNRao", "Jyostna", "Satya", "Prasad", "Sai" };
  System.out.println("\nExtracting names from array starting with \"S\":");
  for(int i = 0; i < names.length; i++)
  {
   if(names[i].startsWith("S"))
   {
    System.out.print(names[i] + ", ");
   }
  }
 }
}


startsWith() String
Output screen on startsWith() String Example

A similar method exists in String class endsWith() checks in from the other end of the string.

Leave a Comment

Your email address will not be published.