Shortest distance between two words in the list
Care about final

Your parameters are never modified, so it is good practice to mark them final. Probably the method too, unless you expect it can be overridden.

public final int shortestDistance(final String[] words, final String word1, final String word2)


Compare by indices

Instead of your for loop, you can use the indices of the elements.

public final int shortestDistance(final String[] words, final String word1, final String word2) {
   final List&lt;String&gt; wordsList = Arrays.asList(words);

  final int word1Index = wordsList.indexOf(word1);
  final int word2Index = wordsList.indexOf(word2);

  return Math.abs(word2Index - word1Index);
}


There could be duplicates

We can solve this problem by finding the index of each occurrence. The final product:

public final int shortestDistance(final String[] words, final String word1, final String word2) {
  final List&lt;Integer&gt; word1Indices = IntStream.range(0, words.length).boxed().filter(i -&gt; words[i].equals(word1)).toList();
  final List&lt;Integer&gt; word2Indices = IntStream.range(0, words.length).boxed().filter(i -&gt; words[i].equals(word2)).toList();

  int result = Integer.MAX_VALUE;

  // Better way to do this but I'm tired.
  for(final Integer word1Index : word1Indices) {
    for(final Integer word2Index : word2Indices) result = Math.min(result, Math.abs(word2Index - word1Index));
  }

  return result;
}