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);
}
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!
No comments:
Post a Comment