.startsWith()
The .startsWith()
method returns true
if a string starts with a given character sequence. Otherwise, false
is returned.
Syntax
string.startsWith(stringOfCharacters);
The stringOfChcaracters
can either be a string literal or a representation of a String
value (variables, constants, etc).
This method will only return case-sensitive matches (i.e. “Word” != “word”).
Example
The following example demonstrates the .startsWith()
method:
import java.io.*;public class Main {public static void main(String[] args) {// With string literalsSystem.out.println("Hello World".startsWith("ello"));// With string objectsString insertBadCoffeePun = "Java";String noMoreJokes = "J";System.out.println("We have had enough of bad coffee puns: " + insertBadCoffeePun.startsWith(noMoreJokes));}}
This will print the following output:
falseWe have had enough of bad coffee puns: true
Contributors
- Anonymous contributor