Ask Question
18 March, 08:58

Write a static method startsWith that inputs two Strings and returns a boolean. If the first input starts with the substring that is the second input, then the method returns true; otherwise, it returns false. For example, startsWith ("radar installation", "rad") returns true startsWith ("radar installation", "installation") returns false startsWith ("radar installation", "") returns true startsWith ("", "a") returns false startsWith ("", "") returns true

+5
Answers (1)
  1. 18 March, 12:22
    0
    The method definition to this question can be given as:

    Method definition:

    public static boolean startsWith (String st1, String st2)

    //define method startsWith

    {

    //conditional statements

    if (st2. length () = = 0)

    //if block

    {

    return true;

    //return value true.

    }

    if (st2. length () > st1. length ())

    //if block

    {

    return false;

    //return value false.

    }

    while (st2. startsWith (" "))

    //while loop

    {

    st2 = st2. substring (1);

    //hold value in st2 variable.

    }

    for (int i = 1; i< = st2. length (); i++)

    //for loop

    {

    if (st1. charAt (st1. length () - i) ! = st2. charAt (st2. length () - i)) / /if block

    {

    return false;

    //return value false

    }

    }

    return true;

    //return value true.

    }

    Explanation:

    In this question, we define the method that is "startsWith () ". The return type of this method is boolean because it returns true or false value only. In this method we pass two string variable that checks the value that can be described as below:

    In this method we define the conditional statement in this statement we check if second string variable that is st2 length is equal to 0. it will return true. Then we define another if block in this block we check if the st2 variable length is grater then to st1 variable so, it will return false. Then we define (while) loop it is an entry control loop in this loop we check st2 variable value is null so it converts st2 variable into substring and holds value into st2 variable. Then we define the (for) loop it is an entry control loop. In this loop, we define conditional statements. In the if block we check st1 variable length is not equal to st2 variable length. if this condition is true it will return false.

    At the end of the program, it will return true. If the above condition is true.
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Write a static method startsWith that inputs two Strings and returns a boolean. If the first input starts with the substring that is the ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers