A fixed-size row of values on the heap. Create arrays two ways, fill them with an index, and loop over them with length.
Java · beginner · 8 min · 20 steps · free
public class ArraysDemo {
public static void main(String[] args) {
int[] marks = new int[4];
marks[0] = 70;
marks[1] = 85;
int[] bonus = {5, 5, 5, 5};
int total = 0;
for (int i = 0; i < marks.length; i++) {
marks[i] = marks[i] + bonus[i];
total += marks[i];
}
System.out.println("Total: " + total + ", length: " + marks.length);
}
}new int[4] makes an array of four ints on the heap, all starting at 0.marks points to, index 1 changes from 0 to 85.total is created on the stack with the value 0.marks.length is 4: the loop runs for i = 0, 1, 2, 3.i changes from 0 to 1.marks points to, index 1 changes from 85 to 90.total changes from 75 to 165.i changes from 1 to 2.total changes from 165 to 170.i changes from 2 to 3.marks points to, index 3 changes from 0 to 5.total changes from 170 to 175.i goes out of scope and disappears.Total: 175, length: 4.Answer: false. boolean arrays start as false.
Answer: 4. Indexes run 0 to 4.
← Pass by Value: Primitives vs References · Two-Dimensional Arrays →