120k views
0 votes
Consider the following incomplete method, which is intended to return the longest string in the string array words. Assume that the array contains at least one element.

public static String longestWord(String[] words)
{
/* missing declaration and initialization */
for (int k = 1; k < words.length; k++)
{
if (words[k].length() > longest.length())
{
longest = words[k];
}
}
return longest;
}

Which of the following can replace /* missing declaration and initialization */ so that the method will work as intended?

a. int longest = 0;
b. int longest = words[0].length();
c. String longest = "";
d. String longest = words[0];
e. String longest = words[1];

User HereTrix
by
5.2k points

2 Answers

8 votes

Final answer:

The correct answer is option d, which is 'String longest = words[0];' This ensures that the longest string in the array 'words' can be found and returned after comparing all strings in the loop.

Step-by-step explanation:

The correct answer to complete the method so that it will return the longest string in the string array words is option d. String longest = words[0];

Option d correctly initializes the variable longest to the first string in the array, allowing the subsequent loop to compare this string with every other string's length. As the loop proceeds and identifies a string longer than the currently stored longest string, it updates the longest variable. This ensures that by the end of the loop, the method will be able to return the actual longest string in the array.

Options a and b use an int type which cannot hold a String value, while option c initializes to an empty string that may not be in the array and thus doesn't serve as a valid comparison base. Option e is incorrect because it assumes the second element in the array is the longest, which is not necessarily true.

User Carmensita
by
5.8k points
11 votes

Answer:

String longest = "";

Step-by-step explanation:

The initialization that would allow the method to work as intended would be the following

String longest = "";

This is because the method is looping through the array provided as an argument and comparing each word in the array with the word saved inside the variable called longest. The length of both are compared and if the word in the array is longer than the string saved in the variable longest then it is overwritten with the word in the array.

User Binz
by
6.0k points