String startsWith() como a sintaxe sugere, este método está presente na classe String que é responsável por testar se uma string começa com o prefixo especificado começando no primeiro índice.

Sintaxe:

public boolean startsWith(String prefix)

Parâmetros: o prefixo a ser correspondido.

Valor de retorno: Ele retorna verdadeiro se a seqüência de caracteres representada pelo argumento for um prefixo da seqüência de caracteres representada por esta seqüência; caso contrário, false.

Métodos:

Existem dois substitutos de startWith() conforme listado abaixo:

  1. Expressões regulares 
  2. método match() da classe String 

Vamos discutir os dois métodos que são os seguintes: 

Método 1: usando expressões regulares

Expressões regulares ou Regex (em resumo) é uma API para definir padrões de String que podem ser usados ​​para pesquisar, manipular e editar uma string em Java. Validação de e-mail e senhas são algumas áreas de strings em que o Regex é amplamente usado para definir as restrições. Expressões regulares são fornecidas no pacote java.util.regex. Este consiste em 3 classes e 1 interface. O pacote java.util.regex consiste principalmente nas três classes a seguir, conforme descrito abaixo em formato tabular, da seguinte maneira:

Exemplo

// java Program to Illustarte Usage of Regular Expressions
// as a Substitute of startWith() method
  
// Importing Matcher and Pattern classes
// from the java.util.regex package
import java.util.regex.Matcher;
import java.util.regex.Pattern;
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
        // Declaring and initialising custom string
        String Str = new String("Welcome to geeksforgeeks");
  
        // Display message for better readibility
        System.out.print(
            "Check whether string starts with Welcome using startsWith : ");
  
        // Testing the prefix using startsWith()
        System.out.println(Str.startsWith("Welcome"));
  
        // Testing the prefix using Regex() by creating
        // objects of Pattern and Matcher class
        Pattern pattern = Pattern.compile("Welcome.*");
        Matcher m = pattern.matcher(Str);
  
        // Print commands
        System.out.print(
            "Check whether string starts with Welcome using Regex: ");
        System.out.println(m.find() ? "true" : "false");
    }
}
Saída
Verifique se a string começa com Welcome usando startsWith: true
Verifique se a string começa com Welcome using Regex: true

Método 2: usando o método Match() da classe String 

 O método String.matchs() informa se esta string corresponde ou não à expressão regular fornecida. Uma invocação desse método da forma str.matches (regex) produz exatamente o mesmo resultado que a expressão Pattern.matches (regex, str).

Sintaxe:

public boolean matches(String regex)

Parâmetros: a expressão regular com a qual esta string deve ser correspondida.

Valor de retorno: este método retorna verdadeiro se, e somente se, essa string corresponder à expressão regular fornecida.

Exemplo

// java Program to Illustarte Usage of String.matches()
// as a Substitute of startWith() method
  
// Importing required classses
import java.util.*;
  
// Main class
public class GFG {
  
    // Main driver method
    public static void main(String args[])
    {
        // Declaring and initialising string
        String Str = new String("Welcome to geeksforgeeks");
  
        // Testing the prefix using startsWith()
        // Work taken - 'Welcome'
        System.out.print(
            "Check whether string starts with Welcome using startsWith : ");
        System.out.println(Str.startsWith("Welcome"));
  
        // Testing the prefix using Regex()
        // Word to be matched - 'Welcome'
        System.out.print(
            "Check whether string starts with Welcome using Matches: ");
        System.out.println(Str.matches("Welcome(.*)"));
    }
}
Saída
Verifique se a string começa com Welcome usando startsWith: true
Verifique se a string começa com Welcome using Matches: true