Java String array - find the longest String in an array of Strings

Java String array tip: Here is the source code for a complete Java class with a method (getLengthLongestString) that demonstrates how to determine the longest String in an array of Strings.

I just updated this example, so it now demonstrates the Java 5 for loop syntax when iterating through the String array.

Source code - the longest String in an array of Strings

public class JavaLongestStringInStringArray
{
  public static String getLengthLongestString(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 = getLengthLongestString(toppings);
    System.out.format("longest string: '%s'\n", longestString);
  }
}

I created this method for use with setting the prototype value for a JList, i.e., using the setPrototypeCellValue method.

Other Java String array and for loop examples

For other examples on how to iterate over a Java String 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.

Java String array - What's Related

As I wrap up my collection of "Java String array" tutorials, here are a few links to my current String array in Java tutorials:

Post new comment

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