Summary - Arrays
- Java course
- Beginner
- Lesson 58/116
- 5 min
Combine declaring, filling and matrices to write a class list.
Summary - Arrays
In this group you learned arrays:
- declaring:
new int[n]and literals - access:
arr[i]andarr.length - filling: index-based
for - multi-dimensional:
int[][]matrix - copying:
System.arraycopy
These structures are the basic tools to process fixed-size data. Now combine them and write a class list.
Practice Class list sum
Write a Main class with a main method. Assign {10, 20, 30} to int[] arr. Assign 0 to int sum. With for (int n : arr) do sum += n. Print the sum with System.out.println(sum).
Sample solution
public class Main {
public static void main(String[] args) {
int[] arr = {10, 20, 30};
int sum = 0;
for (int n : arr) {
sum += n;
}
System.out.println(sum);
}
}Expected output
60
Practice Print a matrix element
Write a Main class with a main method. Assign {{1, 2}, {3, 4}} to int[][] m. Print the top-left element with System.out.println(m[0][0]).
Sample solution
public class Main {
public static void main(String[] args) {
int[][] m = {{1, 2}, {3, 4}};
System.out.println(m[0][0]);
}
}Expected output
1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Can an array's size change after creation?
- Only by adding
- Yes, always
- No, it is fixed Correct answer
- Only by removing
Explanation: An array's size is fixed; it cannot change.
2 Match the array topics
| Term | Meaning |
|---|---|
new int[n] |
Declaring |
arr[i] |
Access |
int[][] |
Matrix |
arraycopy |
Copying |
3 Access the first element
int first = arr[____];
int first = arr[0];
Explanation: arr[0] gives the first element.