This Season
 

How to Get the Index of the String Array in Java

Arrays are one of the primitive type constructors available in the Java programming language. An array can contain elements of a primitive type (e.g., int) or of any reference type. Programs can access directly any element in the array by providing its index, between 0 and the highest index in the array. In particular, an array may contain strings. You can write Java code that determines what index (if any) contains a given string within an array of strings.

Related Searches:
    Difficulty:
    Moderately Easy

    Instructions

      • 1

        Include the following line at the beginning of your Java code:

        import java.lang.String;

      • 2

        Declare and initialize the array of strings and the string you want to search for within the array, as in the following sample code:

        String searchString = "jerop";

        String[] stringArray = {"fomla","anilo","jerop","kuza"};

      • 3

        Loop over all elements in the array while comparing each with the search string, as in the following sample code:

        boolean found = false;

        int foundIndex;

        for (int i=0; i<stringArray.length; i++) {

        if (searchString.equals(stringArray[i])) {

        found = true;

        foundIndex = i;

        break;

        }

        }

        At the end of the loop, if variable "found" is true, then "foundIndex" contains the index within the string array. If "found" is false, the search string was not present within the string array and the index is undefined. For the example, "foundIndex" will get value 2.

    Related Searches

    References

    Read Next:

    Comments

    Follow eHow

    Related Ads