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 (getLengthLongestString) that demonstrates how to determine 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 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 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.)
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.
Post new comment