JAVA 10 Arrays
JAVA 10 Arrays
JAVA 10 Arrays
PROGRAMMING IN JAVA
BATANGAS STATE UNIVERSITY
COLLEGE OF ENGINEERING ARCHITECTURE AND FINE ARTS
PREPARED BY: ENGR. ERWIN S. COLIYAT, LECTURER EE/CPE DEPARTMENT
JAVA ARRAYS
Arrays are used to store multiple values in a single variable, instead of
declaring separate variables for each value.
EXAMPLE:
To find out how many elements an array has, use the
length property:
EXAMPLE:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4
Loop Through an Array
You can loop through the array elements with the for loop, and
use the length property to specify how many times the loop
should run.
The following example outputs all elements in the cars array:
EXAMPLE
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
Multidimensional Arrays
We can also use a for loop inside another for loop to get the elements of a
two-dimensional array (we still have to point to the two indexes):
EXAMPLE
public class MyClass {
public static void main(String[] args) {
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
for (int i = 0; i < myNumbers.length; ++i) {
for(int j = 0; j < myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);
}
}
}
}