If you want to get whether a string starts with a specified string, you can use the java.lang.String class's two overloaded startsWith() method. It returns true if the string contains the prefix or false otherwise.
In single argument startsWith() method, the only argument is the string that is the prefix in the specified string.
In two argument startsWith() method, the first argument is the prefix and the second one is the position or offset, from where you would like to check.
Some points about the startsWith() method is given below:
Method Declaration:
public boolean startsWith(String prefix)
public boolean startsWith(String prefix, int toffset)
Live Example:
Output:
url: Learn Java API
url.startsWith("Learn"): true
url.startsWith("L"): true
url.startsWith(""): true
url.startsWith("Java"): false
url.startsWith("Learn Java API Now"): false
url.startsWith("Learn", 0): true
url.startsWith("Learn", 1): false
url.startsWith("Java", 6): true
url.startsWith("Java", 5): false
Use the social sharing button below to spread the knowledge among others.
In single argument startsWith() method, the only argument is the string that is the prefix in the specified string.
In two argument startsWith() method, the first argument is the prefix and the second one is the position or offset, from where you would like to check.
Some points about the startsWith() method is given below:
- You can use this method with string literal. Example: "Java".startsWith("J").
- If you pass null as the first argument to this method, it will always return true.
Method Declaration:
public boolean startsWith(String prefix)
public boolean startsWith(String prefix, int toffset)
Live Example:
public class Demo { public static void main(String[] args) { String url = "Learn Java API"; System.out.println("url: " + url); System.out.println("url.startsWith(\"Learn\"): " +url.startsWith("Learn")); System.out.println("url.startsWith(\"L\"): " + url.startsWith("L")); System.out.println("url.startsWith(\"\"): " + url.startsWith("")); System.out.println("url.startsWith(\"Java\"): " + url.startsWith("Java")); System.out.println("url.startsWith(\"Learn Java API Now\"): " + url.startsWith("Learn Java API Now")); System.out.println("url.startsWith(\"Learn\", 0): " + url.startsWith("Learn", 0)); System.out.println("url.startsWith(\"Learn\", 1): " + url.startsWith("Learn", 1)); System.out.println("url.startsWith(\"Java\", 6): " + url.startsWith("Java", 6)); System.out.println("url.startsWith(\"Java\", 5): " + url.startsWith("Java", 5)); } }
Output:
url: Learn Java API
url.startsWith("Learn"): true
url.startsWith("L"): true
url.startsWith(""): true
url.startsWith("Java"): false
url.startsWith("Learn Java API Now"): false
url.startsWith("Learn", 0): true
url.startsWith("Learn", 1): false
url.startsWith("Java", 6): true
url.startsWith("Java", 5): false
Use the social sharing button below to spread the knowledge among others.