Answer:
public static String longestWord(String input) {
// split the input string into an array of words
String[] words = input.split(" ");
// initialize the longest word to be the first word in the array
String longestWord = words[0];
// initialize the index of the current word to 1
int i = 1;
// loop through the remaining words in the array
while (i < words.length) {
// if the current word is longer than the longest word,
// update the longest word to be the current word
if (words[i].length() > longestWord.length()) {
longestWord = words[i];
}
// move to the next word in the array
i++;
}
// return the longest word
return longestWord;
}
Step-by-step explanation:
To use this method, you can call it with a string argument, like this:
String sentence = "he plays an interesting sport";
String longestWord = longestWord(sentence);
// the variable 'longestWord' should now be "interesting"
Note that this method does not use arrays, as requested in the question. Instead, it uses a while loop to iterate over the words in the input string.