Java: How to find the longest String in an array of Strings

Java String array FAQ: Can you share an example of how to determine the largest String in a Java String array?

Sure, in this short tutorial I’ll share the source code for a complete Java class with a method that demonstrates how to find the longest String in a Java string array.

Finding the longest string in a Java string array

Here’s the source code that shows how to find the longest string in a Java String array:


public class JavaLongestStringInStringArray {

  public static String getLongestString(String[] array) {
      int maxLength = 0;
      String longestString = null;
      for (String s : array) {
          if (s.length() > maxLength) {
              maxLength = s.length();
              longestString = s;
          }
      }
      return longestString;
  }

  public static void main(String[] args) {
      String[] toppings = {"Cheese", "Pepperoni", "Black Olives"};
      String longestString = getLongestString(toppings);
      System.out.format("longest string: '%s'\n", longestString);
  }

}

I recently created this method for use with setting the prototype value for a JList, i.e., using the setPrototypeCellValuemethod. (If you haven't used it before, when using a JList, it can be very helpful to know the length of the longest String in your Java String array.)

Other Java String array and for loop examples

For other examples on how to iterate over a Java array, check out this tutorial on How to loop through a Java String array with the Java 5 for loop syntax.