Introduction to Arrays
What is an Array?
• An array is a collection of elements of the same data type stored in contiguous memory locations.
• Each element in the array can be accessed using an index.
Analogy:
• Think of an array as a row of mailboxes, each holding one value and labeled with an index
number.
Example:
int[] scores = new int[5];
This creates an array named scores that can store 5 integers.
Why Use Arrays?
• To store large amounts of related data efficiently.
• Easy access to any element using index numbers.
• Simplifies repetitive operations using loops.
• Forms the foundation for more complex data structures (lists, stacks, queues,
etc.).
Array Syntax
Declaration:
int[] numbers;
Allocation:
numbers = new int[5];
Combined Declaration & Allocation:
int[] numbers = new int[5];
Initialization (assigning values):
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
Shortcut Initialization:
int[] numbers = {10, 20, 30, 40, 50};
Array Memory & Indexing
How Arrays Work in Memory
• Stored in contiguous memory locations.
• Indexing starts from 0.
• The length property tells how many elements are in the array.
[Link]([Link]); // Output: 5
Common Mistake.
int[] arr = new int[3];
arr[3] = 10; // Error! Index 3 doesn’t exist (valid are 0,1,2)
Exception: ArrayIndexOutOfBoundsException
Visual Representation
index 0 1 2 3 4
Values 10 20 30 40
Practice 1: Basic Array
Write a Java program to:
Create an array of 5 integers.
Assign values manually.
Print all elements using a for loop.
Iterating Through Arrays
• Using for Loop
int[] nums = {2, 4, 6, 8, 10};
for (int i = 0; i < [Link]; i++) {
[Link]("Element at index " + i + ": " + nums[i]);
}
• Enhanced for-each Loop
for (int num : nums) {
[Link](num);
}
• Note: You can’t access the index directly in a for-each loop.
• Practice 2:
LoopingCreate a program that prints all even numbers in an array.
Array Operations
• Updating Array Elements
int[] data = {10, 20, 30};
data[1] = 50;
• Summing Array Elements
int sum = 0;
for (int val : data) {
sum += val;
}
Finding the Maximum Value
int max = data[0];
for (int val : data) {
if (val > max) max = val;
}
[Link]("Max value: " + max);
Practice 3:
• Write a program to:
Take an array of integers.
Calculate the average value.
Print elements greater than the average.
String Arrays
• Declaration
String[] names = {"Ali", "Bola", "Chioma", "David"};
• Loop Through
for (String name : names) {
[Link]("Hello, " + name);
}
Practice 4:
• Write a program to:
Store 4 course names in a string array.
Print them all in uppercase.
Two-Dimensional Arrays (2D Arrays)
Concept
Arrays that store data in rows and columns, like tables or matrices.
• Declaration:
int[][] matrix = new int[3][3];
• Initialization:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
}
Accessing Elements
[Link](matrix[1][2]); // Output: 6
• Nested Loops for Traversal
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
[Link](matrix[i][j] + " ");
}
[Link]();
}
Practice 5:
• Create a 3×3 array.
• Fill it with random numbers between 1 and 9.
• Print the diagonal elements only.
Common Errors and Debugging Tips
Error Type Example Explanation
ArrayIndexOutOfBounds arr[5] when size is 5 Indexes go from 0–4
NullPointerException [Link] when arr = null Array not initialized
Logic Errors Wrong loop bounds Example: i <= [Link]
Error Type Example Explanation
Debugging Tips
Always use [Link] instead of hardcoding the array size.
Use print statements to trace loops.
Test edge cases like first and last elements.
Mini Project:
• Student Score AnalyzerRequirements:
1. Ask the user to enter 5 student scores.
2. Store them in an array.
3. Find and print:
• Average score
• Highest and lowest score
• All scores above average
Class Discussion Question
• What are the advantages and disadvantages of arrays?
• Why is array length fixed in Java?
• How can you handle data when the number of elements is unknown?
• What’s the difference between a 1D and 2D array?
• How can you detect errors like ArrayIndexOutOfBounds early?