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 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.

If you have any comments or suggestions, please feel free to leave a message in the comment section below.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.