String
String startsWith method
In this example we shall show you how to use the startsWith
method of String class. The String class represents character strings. All string literals in Java programs, such as "abc"
, are implemented as instances of this class. To check if a String starts with a specified prefix one should perform the following steps:
- Create a new String.
- Use
startsWith(String prefix)
API method of String. It tests if this string starts with the specified prefix,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; public class StringStartsWithMethod { public static void main(String[] args) { String s = "Java Code Geeks"; if (s.startsWith("Java")) { System.out.println("String starts with Java"); } else { System.out.println("String does not start with Java"); } if (s.startsWith("Unknown")) { System.out.println("String starts with Unknown"); } else { System.out.println("String does not start with Unknown"); } } }
Output:
String starts with Java
String does not start with Unknown
This was an example of startsWith
method of String in Java.