Arrays and ArrayLists
💻 JavaStore fixed-size arrays and resizable lists, then loop through them safely.
Arrays hold a fixed number of values. ArrayList grows as needed and is usually the better default for collections.
- Create and iterate arrays.
- Use ArrayList methods.
- Avoid index errors.
Arrays
An array has a fixed length set at creation. Indexes start at zero and end at length minus one.
int[] scores = {88, 74, 91, 65};
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
for (int score : scores) {
System.out.println(score);
}ArrayList
ArrayList resizes automatically. Import it from java.util and use wrapper types such as Integer instead of primitives.
import java.util.ArrayList;
ArrayList<String> subjects = new ArrayList<>();
subjects.add("Mathematics");
subjects.add("English");
subjects.add("Physics");
System.out.println(subjects.size());
System.out.println(subjects.get(0));
subjects.remove("English");Common Mistakes
Accessing an index equal to the length throws ArrayIndexOutOfBoundsException. Removing items while looping over a list can skip elements; iterate over a copy or use an iterator.
Practice
- Create an array of five scores and print the highest.
- Add three names to an ArrayList and print them.
- Remove one item and print the new size.
Hands-on exercise
Write a program with an int array of six scores.
1. Calculate the average.
2. Print the average to one decimal place.
3. Print every score above the average.
Recap
Arrays are fixed and fast. ArrayList is flexible and easier for most application work.
Example
int[] scores = {88, 74, 91, 65};
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
for (int score : scores) {
System.out.println(score);
}
Exercises
1. Calculate the average.
2. Print the average to one decimal place.
3. Print every score above the average.
Expected Output
Average: 74.8 followed by the scores above it.
Lesson Nav
Java Course
0/9 lessons completed
- 1 Getting Started with Java Tutorial
- 2 Variables and Data Types Tutorial
- 3 Conditions and Loops Tutorial
- 4 Methods and Parameters Tutorial
- 5 Arrays and ArrayLists Tutorial
- 6 Classes and Objects Tutorial
- 7 Inheritance, Interfaces and Polymorphism Tutorial
- 8 Exceptions and Files Tutorial
- 9 Project: A Console Grade Book Project