Arrays
are variables that can store many values.
Keep in mind that Arrays are Indexed starting at 0.
public class ExampleClass {
public static void main(String[] args) {
String[] pets = {"dog","cat","fish","bird"};
System.out.println(pets[0]);
}
}
Output
dog
Array length
Get the length of an Array by using length
For the code below, the output is 3.
public class Example{
public static void main(String[] args) {
String [] pets = {"dog","cat","fish"};
System.out.println(pets.length);
}
}
Array Loop
for
loop can be used to output all elements within an array.
public class Main{
public static void main(String[] args) {
String[] pets = {"dog", "cat", "fish", "bird"};
for (int i = 0; i < pets.length; i++) {
System.out.println(pets[i]);
}
}
}
Output :
dog
cat
fish
bird
Multidimensional Arrays
are arrays that hold many other arrays.
Each array is separated by curly brackets {}
public class Example {
public static void main(String[] args) {
int[][] Salaries = { {22000, 25000, 38000, 42000}, {87000, 69000, 71000} };
for (int partTime = 0; PartTime < Salaries.length; ++ PartTime)
{
for(int fullTime = 0; fullTime < Salaries[partTime].length; ++ fullTime) {
System.out.println(Salaries[partTime][fullTime]);
}
}
}
}
Output
22000
25000
38000
42000
57000
66000
71000