Dee Dee - 1 year ago 77
Java Question

Finding the longest string in an array of Strings

The problem with this is that i tried to do it but my method to check the length of the string is not working; what can I do to fix it?

public static void main(String[] args) {
String[] animalNames = {"cat", "rabbit", "horse", "goat", "rooster", "ooooooooooooooo"};
String a= getLongestString(animalNames);

public static String getLongestString(String []animalNames) {
// String animalNames[] = {"cat","chicken","horse","ooooooooo" };

int j = 0;
for (j = 0; j <= animalNames.length; j++) {
if (animalNames[j].length() > animalNames[j + 1].length()) {
return (animalNames[j]);
return null;


Answer Source

Here. 1. You use j<= animalNames.length;?

  1. You compare animalNames[j + 1]? -> error index out of array

  2. and you return in the first if condition return (animalNames[j]); -> wrong value

Ok, let me make clear. You find the longest string in an array. You loop over the array then you compare 2 near elements, and then return the bigger one. With your code, it will return the rabbit. Right?

May be you confuse about the process flow. There is a simple way.

  1. You assign a variable for the length of the first array element: elementLength = array[0].length; and a value to keep track of the index
  2. You loop over the array You check every element with this variable, if bigger then re-assign the element value and update the index.
  3. End of the loop. you have the biggest length and the index


int index = 0; 
int elementLength = array[0].length();
for(int i=1; i< array.length(); i++) {
    if(array[i].length() > elementLength) {
        index = i; elementLength = array[i].length();
return array[index];

that is it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download