Consider the following two code segments, which are both intended to determine the longest of the three strings "pea", "pear", and "pearl" that occur in String str. For example, if str has the value "the pear in the bowl", the code segments should both print "pear" and if str has the value "the pea and the pearl", the code segments should both print "pearl". Assume that str contains at least one instance of "pea".

I) if (str.indexOf("pea") >= 0)
{System.out.println("pea");}
else if (str.indexOf("pear") >= 0)
{System.out.println("pear");}
else if (str.indexOf("pearl") >= 0)
{System.out.println("pearl");}

II) if (str.indexOf("pearl") >= 0)
{System.out.println("pearl");}
else if (str.indexOf("pear") >= 0)
{System.out.println("pear");}
else if (str.indexOf("pea") >= 0)
{System.out.println("pea");}

Which of the following best describes the output produced by code segment I and code segment II?

a) Both code segment I and code segment II produce correct output for all values of str.
b) Neither code segment I nor code segment II produce correct output for all values of str.
c) Code segment II produces correct output for all values of str, but code segment I produces correct output only for values of str that contain "pear" but not "pearl".
d) Code segment II produces correct output for all values of str, but code segment I produces correct output only for values of str that contain "pearl".
e) Code segment II produces correct output for all values of str, but code segment I produces correct output only for values of str that contain "pea" but not "pear".

Respuesta :

Answer:

e) Code segment II produces correct output for all values of str, but code segment I produces correct output only for values of str that contain "pea" but not "pear".

Explanation:

if - elseif - else statements work in sequence in which they are written.

  • In case if() statement is true, else if() and else statements will not get executed.
  • In case else if() statement is true, conditions in if() and else if() will be checked and else statement will not be executed.
  • In case if() and else if() both are false, else statement will be executed.

First, let us consider code segment I.

In this, first of all "pea" is checked in if() statement which will look for "pea" only in the String str. So, even if "pearl" or "pear" or "pea" is present in 'str' the result will be true and "pea" will get printed always.

After that there are else if() and else statements which will not get executed because if() statement was already true. As a result else if() and else statements will be skipped.

Now, let us consider code segment II.

In this, "pearl" is checked in if() condition, so it will result in desired output.

Executable code is attached hereby.

Correct option is (e).

Ver imagen isyllus
Ver imagen isyllus
Q&A Education