Suppose strArray is an array of String objects that has been declared, created, and filled.
// start out with the maximum length being the length of the first string // and the location of where the maximum length occurs being the first string int maxLength = (strArray[0] == null) ? 0 : strArray[0].length; // this takes into account the possibility that the first item is null int maxIndex = 0; for (int i = 0; i < strArr.length; i++) { if (strArr[i] != null && // only consider non-null array locations strArr[i].length() > maxLength) { // if we've found a longer string maxLength = strArr[i]; // update the max info maxIndex = i; } }
If there is a tie, this code will find the index of the first item with the
maximum length (because we used ">", if we had used ">=" then we would have found
the index of the last such item). Note that empty strings are not a
concern - they are just String objects (with a length of 0).