English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input and output (I/O)

Java Reader/Writer

Java other topics

Java String startsWith() usage and example

Java String (String) Methods

The Java String startsWith() method checks if the string starts with the specified string.

The syntax of the string.startsWith() method is:

string.startsWith(String str, int offset)

Here, string is an object of the String class.

startsWith() parameters

  • str - Check if the string starts with str

  • offset(Optional)-  Check the substring of the string(string) starting from this index.

startsWith() return value

  • If the string starts with the given stringReturns true

  • If the string does not start with the given stringReturns false

Example1Java startsWith() without offset parameter

class Main {
  public static void main(String[] args) {
    String str = "Java Programming";
    System.out.println(str.startsWith("Java")); // true
    System.out.println(str.startsWith("J")); // true
    System.out.println(str.startsWith("Java Program")); // true
    System.out.println(str.startsWith("java")); // false
    System.out.println(str.startsWith("ava")); // false
  }
}

As can be seen from the above example, startsWith() is case-sensitive (lowercase and uppercase).

Example2: Java startsWith() with offset (offset) parameter

class Main {
  public static void main(String[] args) {
    String str = "Java Programming";
    // Check substring "a Programming"
    System.out.println(str.startsWith("Java", 3)); // false
    System.out.println(str.startsWith("a Pr", 3)); // true
  }
}

Here, we pass through3as the offset. Therefore, in the above program, startsWith() checks if 'a Programming' starts with the specified string.

If you need to check if a string ends with a specified string, please useJava String startsWith()Methods.

Java String (String) Methods