Thursday, 8 September 2011

Java: Arrays II

    Let's start off with the foreach loop today. Remember yesterday, when filling out the elements of the array, we had a for loop to iterate over each element? Well, while that's a perfectly reasonable method to do so, and in fact, the method I personally prefer, there's a separate way to do this, known as the foreach loop.


    public static void main(String[] argv) {

        int[] exampleArray = new int[3];
        exampleArray[0] = 1;
        exampleArray[1] = 2;
        exampleArray[2] = 3;//just doing it this way since the for loop is as many lines for such a short array.

        int sumOfElements = 0;

        for ( int currentValue : exampleArray ) {
            sumOfElements += currentValue;
        }
        
        System.out.println(sumOfElements);
    }

    The purple bit is the foreach loop, it just takes each integer (in this case) inside the array provided, and performs the loop body on it. Simple stuff, makes for loops easier when iterating over entire arrays.

    As with basically anything else, you can use arrays as return values as well as parameters, but keep in mind that the pointer to the array is used in both cases. This means you cannot return an array, and print it out, expecting to see all the elements within, but you can call an index of the returned value.

public int[] arrayFunction() {
    // calculate array elements etc.
    return integerArray;
}


int[] exampleArray = arrayFunction();


System.out.println(exampleArray); //This is useless, you'll get a seemingly random assortment of characters that are used to tell the computer where to look in memory to get the array


System.out.println( exampleArray[ someIndex ]; //This is good, and useable!






This is it for tonight. Follow, comment, share etc. See you tomorrow!

1 comment:

  1. Question, is -int the same as init or initial, initialize and what do you use to compile, or does it even need a compiler - i use Linux, gcc

    ReplyDelete