Arrays & ArrayLists
By: Prince Emmanuel Ndoinjeh
Objectives
By the end of this session, students will be able to:
Declare, initialize, and use one-dimensional arrays
Use for loops to traverse arrays
Apply common array algorithms (sum, average, min/max, search)
Write functions that operate on arrays
Declare and initialize an ArrayList
Use add(), remove(), get(), set(), and size()
Understand the differences between ArrayList and arrays
Practice iterating over ArrayList values using loops
BlueCrest Liberia 2
What Is a List of Data?
A list of data is simply a way to group related pieces of information together.
Instead of storing each item in a separate variable, a list lets you store all of
them in one place. For example:
String fruit1 = "Apple";
String fruit2 = "Banana";
String fruit3 = "Mango";
This works, but imagine managing hundreds of fruits—it quickly gets messy.
BlueCrest Liberia 3
What Is an Array?
An array is a data structure that lets you store multiple values of the same
type in a single variable. You access each item by its position in the array,
called an index.
String[] fruits = {"Apple", "Banana", "Mango"};
System.out.println(fruits[0]); // Outputs "Apple"
System.out.println(fruits[2]); // Outputs "Mango"
Key Features:
Fixed size: You define the number of elements when the array is created.
Indexed access: Items are accessed using a numerical index, starting at 0.
Type-specific: All items must be of the same data type (like int, String, etc.).
BlueCrest Liberia 4
Common Uses of Arrays
Arrays are useful in scenarios like:
Storing scores for multiple players in a game
Listing products in an online store
Handling student grades in a classroom
int[] scores = {89, 95, 72, 100};
You can loop through arrays, modify elements,
or use them to build more complex systems.
BlueCrest Liberia 5
Syntax of Arrays
To create an array, you use square brackets [] after the data type.
int[] scores = {85, 90, 78, 100};
String[] fruits = {"Apple", "Banana", "Mango"};
Key Points:
Arrays are declared with a type (int, String, etc.) followed by [].
Values are enclosed in {} and separated by commas.
BlueCrest Liberia 6
Fixed Size
Arrays in Java have a fixed length once they’re created. You can’t change the size
afterward (though you can change individual values).
int[] numbers = new int[4]; // Creates an array with 4 elements
numbers[0] = 10;
numbers[1] = 20;
Even if the array is empty at first, its size is locked at creation:
System.out.println(numbers.length); // Outputs: 4
Want dynamic sizing? That’s when ArrayList comes in handy—but we’ll save that for later 😉
BlueCrest Liberia 7
Indexing
Every array element is accessed using its index, starting from 0.
String[] animals = {"Dog", "Cat", "Elephant"};
System.out.println(animals[1]); // Outputs "Cat"
Pro Tip:
Trying to access an index outside the array range (like animals[3]) causes
an error called ArrayIndexOutOfBoundsException.
BlueCrest Liberia 8
For Loop to Print Array Elements
String[] fruits = {"Apple", "Banana", "Mango"};
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}
You can also use an enhanced for loop (AKA “for-each”) when you don't need the index:
for (String fruit : fruits) {
System.out.println(fruit);
}
BlueCrest Liberia 9
Sum of Numbers in an Array
int[] scores = {85, 90, 78, 100};
int sum = 0;
for (int i = 0; i < scores.length; i++) {
sum += scores[i];
}
System.out.println("Total score: " + sum);
BlueCrest Liberia 10
Count Specific Elements
Let’s count how many scores are 90 or above:
int count = 0;
for (int i = 0; i < scores.length; i++) {
if (scores[i] >= 90) {
count++;
}
}
System.out.println("Number of high scores: " +
count);
BlueCrest Liberia 11
Code challenge: find the first A grade
public class FirstAGradeFinder {
public static void main(String[] args) {
int[] scores = {75, 88, 79, 92, 85, 95}; // Example scores
for (int i = 0; i < scores.length; i++) {
if (scores[i] >= 90) {
System.out.println("First A grade found: " + scores[i]);
break; // Stop once we find the first A
}
}
}
}
BlueCrest Liberia 12
Why Arrays Can Be Limiting
1. Fixed Size
Once you create an array, its size is locked:
• int[] scores = new int[5]; // Always 5 elements, even if some are unused
Can’t shrink or expand based on user input or dynamic data
Leads to wasted memory or frustrating capacity errors
Date Your Footer Here 13
Why Arrays Can Be Limiting
2. Manual Management
You have to:
Keep track of index positions manually
Write custom logic for adding, removing, or shifting elements
For example, deleting an item means shifting all the later items left—
no built-in method does that.
Date Your Footer Here 14
Why Arrays Can Be Limiting
3. No Built-in Methods
Unlike higher-level structures, arrays lack helpful methods like:
.add(), .remove(), .contains(), .indexOf()
You end up writing more boilerplate code just to do simple tasks.
Date Your Footer Here 15
Why Arrays Can Be Limiting
4. Type Rigid
Arrays hold only one data type:
String[] names = {"Alice", "Bob"}; // You can’t mix with integers or booleans
In real-world use (like a restaurant screen that mixes item names, prices,
and availability), this rigid typing becomes a hassle.
Date Your Footer Here 16
When to Use Arrays vs ArrayList
Feature Array ArrayList
Size Fixed Dynamically resizable
Methods Few (length) Many (add, remove, contains)
Flexibility Low High
Slightly slower but more
Performance Faster (for small, fixed data) versatile
Ideal for Primitive data Complex app logic, user-driven
data
Date Your Footer Here 17
What is an ArrayList in Java?
An ArrayList is a resizable array — a flexible data structure that
stores a list of elements and can grow or shrink as needed.
How to Use It
To use ArrayList, you must import it from Java’s java.util package:
import java.util.ArrayList;
Then create one:
ArrayList<String> names = new ArrayList<>();
Date Your Footer Here 18
ArrayList - Adding Elements
• You can now:
names.add("Alice"); // Add an element
names.get(0); // Get element at index 0
names.set(0, "Bob"); // Replace element at index
0names.remove(0); // Remove element at index
0names.size(); // Get the number of elements
Date Your Footer Here 19
ArrayList - Removing Elements
• fruits.remove("Banana"); // Removes by value
• fruits.remove(0); // Removes by index
Note: If you remove by index, it shifts elements automatically.
Date Your Footer Here 20
ArrayList - Getting Elements
• String firstFruit = fruits.get(0); // Get item at index 0
• System.out.println(firstFruit); // Outputs "Mango" (after adding)
Date Your Footer Here 21
ArrayList - Setting (Updating) Elements
fruits.set(1, "Pineapple"); // Replace value at index 1
Example: changes "Banana" to "Pineapple".
Checking Size
System.out.println("Total fruits: " + fruits.size());
Unlike arrays, ArrayList.size() changes dynamically as you add or remove items.
Date Your Footer Here 22
Summary Table
Action Syntax Example Description
Declare ArrayList<String> list = new ArrayList<>(); Create an empty list
Add list.add("Item") Add item to end
Remove list.remove("Item"), list.remove(index) Remove by value or index
Get list.get(index) Access item by index
Set list.set(index, "New Value") Update item at given index
Size list.size() Get current number of items
Date Your Footer Here 23
Prince Emmanuel Ndoinjeh
+231555169548
Bluecrest Liberia
Thank You!
BlueCrest Liberia 24