Java · Lesson 8 of 15
Arrays
Fixed-size arrays, loops over them, 2D arrays and the Arrays utility class.
- Beginner
- 12 min read
- 3 objectives
Before this lessonLesson 7: Strings and StringBuilder
What you will learn
- Create and index arrays
- Loop with for and for-each
- Sort and print with Arrays
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
An array holds a fixed number of values of one type, stored side by side and accessed by index starting at 0. The length is set when you create it and cannot change.
Creating and reading
public class Main {
public static void main(String[] args) {
int[] scores = new int[3]; // {0, 0, 0}
scores[0] = 90;
int[] primes = {2, 3, 5, 7};
System.out.println(scores[0] + " " + primes.length);
System.out.println(primes[primes.length - 1]);
}
}Output
90 4 7
Reading past the end throws ArrayIndexOutOfBoundsException; valid indexes are 0 to length - 1.
Looping
public class Main {
public static void main(String[] args) {
int[] nums = {4, 8, 15};
int sum = 0;
for (int n : nums) {
sum += n;
}
System.out.println(sum);
for (int i = 0; i < nums.length; i++) {
System.out.println(i + ": " + nums[i]);
}
}
}Output
27 0: 4 1: 8 2: 15
The Arrays helper class
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] a = {5, 2, 9, 1};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
System.out.println(Arrays.binarySearch(a, 5));
int[] copy = Arrays.copyOf(a, 6);
System.out.println(Arrays.toString(copy));
System.out.println(Arrays.equals(a, copy));
}
}Output
[1, 2, 5, 9] 2 [1, 2, 5, 9, 0, 0] false
Two-dimensional arrays
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[][] grid = {{1, 2, 3}, {4, 5, 6}};
System.out.println(grid[1][2]);
System.out.println(Arrays.deepToString(grid));
}
}Output
Methods and OverloadingParameters, return values, overloading, varargs and pass-by-value.
6 [[1, 2, 3], [4, 5, 6]]
