Java Arrays Single Dimensional Arrays 

advertisement
Java Arrays
Single Dimensional Arrays







An array is a sequence of variables of the same data type (homogenous).
The data type can be any of Java’s primitive types or a class (user-defined as well).
Each variable in the array is an element.
We use an index to specify the position of each element in the array.
Arrays are useful for many applications, including calculating statistics or representing the state of a
game.
Array indexes always begin with zero (0).
In Java Arrays are objects, so they need to be declared and instantiated
Example 1: Declaring an array when the number of elements are known. The elements are initialized
after by assigning values to each element in the array starting at index 0.
Output: 543
Example 2:
Result:
Example 3: THIS ONE ROLLS A DICE 1000 TIMES. IT COUNTS THE FREQUENCY OF THE NUMBER THAT
SHOWS UP
Example 4: Initializing the elements in the array declaration
Example 5: SUMMING ELEMENTS OF AN ARRAY
Output: The sum of these numbers is 147
Example 6
Example 7
Example 8: This code produces an error.
Example 9: Enhanced For loop
This is different from the above because it has less code.
They array is called Names
In the For loop a new string variable is declared called name
Every time the loop iterates, the value of name changes as it goes through each index/element of the
array.
Download