Chapter 6: Arrays
Metadata
| Field | Value |
|---|---|
| Chapter | 6 |
| Topic | Arrays |
| Prerequisite | Methods, Control Flow, Variables and Data Types |
| Estimated Time | 150-180 minutes |
| Outcome | Store, access, update, and process multiple values of the same type using Java arrays |
1. Purpose
This chapter introduces arrays as Java's foundational structure for storing multiple values under one logical name. If variables store one value and methods organize reusable behavior, arrays make it possible to manage collections of related data efficiently.
An array is one of the first data structures a Java student must truly understand. It introduces indexed access, contiguous logical organization, traversal patterns, and the distinction between a single value and a structured group of values.
2. Problem Statement
Without arrays, programs that handle repeated data become unnecessarily large and fragile.
Common problems include:
- creating too many separate variables for related values
- repetitive code for reading or printing similar data
- difficulty applying loops to grouped information
- weak preparation for later structures such as collections, strings, matrices, and objects
A program that needs to process many values must have a structured way to store them. Arrays provide that first structured solution.
3. Core Definitions
3.1 Array
An array is a fixed-size indexed structure that stores multiple values of the same type.
General model:
Array = One Name + Many Indexed Values + One Common Type
Example:
int[] marks = {85, 90, 78, 92};
In this declaration:
marksis the array variableint[]is the array type- the array contains four integer elements
3.2 Element
Each individual value inside an array is called an element.
For example:
marks[0]
marks[1]
Each indexed position refers to one element.
3.3 Index
An index is the numeric position used to access an element in an array.
Java arrays are zero-based:
- first element -> index
0 - second element -> index
1 - last element -> index
length - 1
This rule is fundamental and never changes.
4. Array Characteristics
Arrays in Java have several defining properties:
- all elements must have the same type
- the size is fixed after creation
- elements are accessed using indexes
- arrays are reference types
- each array knows its own length through the
lengthfield
Important Implication
An array variable does not directly store all element values in the same way a primitive variable stores a primitive. Instead, the variable refers to an array object managed by the JVM.
That means arrays behave differently from plain primitives in memory and when passed to methods.
5. Declaration and Initialization
There are several standard ways to declare and create arrays in Java.
5.1 Declaration Only
int[] numbers;
This declares an array variable but does not create the array itself yet.
5.2 Declaration With Creation
int[] numbers = new int[5];
This creates an array that can hold five integers.
Default values are assigned automatically:
- numeric types ->
0 boolean->falsechar->'\u0000'- reference types ->
null
5.3 Declaration With Initial Values
int[] numbers = {10, 20, 30, 40, 50};
This both creates the array and fills it with values.
5.4 Equivalent Explicit Form
int[] numbers = new int[] {10, 20, 30, 40, 50};
This form is especially useful when passing an array directly to a method.
6. Array Memory Model
The conceptual model is:
Array Variable -> Array Object -> Indexed Elements
Example:
int[] values = new int[3];
Conceptually:
values -> [0, 0, 0]
After updates:
values[0] = 10;
values[1] = 20;
values[2] = 30;
Conceptually:
values -> [10, 20, 30]
Mental Model
An array is one object that contains many positions. You do not create five separate variable names for five values. Instead, you create one structure and use indexes to address its internal positions.
7. Accessing and Updating Elements
Read an Element
int[] marks = {85, 90, 78};
System.out.println(marks[1]);
Output:
90
Update an Element
marks[2] = 88;
Now the array becomes:
[85, 90, 88]
Access the Last Element
System.out.println(marks[marks.length - 1]);
Using length - 1 is the safe general pattern for the final valid index.
8. Traversing Arrays
Traversal means visiting each element in sequence.
8.1 Using a for Loop
int[] numbers = {10, 20, 30, 40};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
This is the most flexible approach because the index is available.
8.2 Using an Enhanced for Loop
Java also provides the enhanced for loop:
int[] numbers = {10, 20, 30, 40};
for (int number : numbers) {
System.out.println(number);
}
This is easier to read when:
- you only need the element value
- you do not need the index
Choosing Between the Two
- use a standard
forloop when you need indexes or want to modify specific positions - use an enhanced
forloop when you only need to read values
9. Arrays and Methods
Arrays are frequently passed to methods because they allow one method to process many values.
Example
public class ArrayMethodDemo {
public static void main(String[] args) {
int[] scores = {80, 90, 70};
printArray(scores);
}
static void printArray(int[] values) {
for (int value : values) {
System.out.println(value);
}
}
}
Important Rule
Java still uses pass-by-value.
When an array is passed to a method:
- the reference value is copied
- both caller and method refer to the same underlying array object
That means element updates inside the method are visible outside the method.
Example:
public class ArrayUpdateDemo {
public static void main(String[] args) {
int[] data = {1, 2, 3};
changeFirst(data);
System.out.println(data[0]); // 99
}
static void changeFirst(int[] values) {
values[0] = 99;
}
}
This does not contradict pass-by-value. The copied value is the reference, and that reference still points to the same array object.
10. Code Example
public class ArraysDemo {
public static void main(String[] args) {
int[] marks = {85, 90, 78, 92};
System.out.println("First Mark: " + marks[0]);
System.out.println("Total Elements: " + marks.length);
marks[2] = 88;
for (int i = 0; i < marks.length; i++) {
System.out.println("Index " + i + ": " + marks[i]);
}
}
}
Analysis
This example demonstrates several core array operations:
- array creation with initial values
- indexed access
- indexed update
- use of the
lengthfield - traversal with a
forloop
11. Constraints and Rules
The following rules are fundamental:
- array indexes must be integers
- valid indexes range from
0tolength - 1 - all elements must match the declared array type
- array size cannot be changed after creation
- the array variable must refer to a valid array object before access
About length
For arrays, length is a field, not a method.
Correct:
numbers.length
Incorrect:
numbers.length()
That distinction matters because strings use length() while arrays use length.
12. Failure Scenarios
Failure cases reveal the real boundaries of array behavior.
12.1 Index Out of Bounds
int[] numbers = {10, 20, 30};
System.out.println(numbers[3]);
Result:
- runtime exception:
ArrayIndexOutOfBoundsException
Reason:
- valid indexes are
0,1, and2 - index
3is outside the array boundary
12.2 Negative Index
int[] numbers = {10, 20, 30};
System.out.println(numbers[-1]);
Result:
- runtime exception:
ArrayIndexOutOfBoundsException
Reason:
- array indexes cannot be negative
12.3 Type Mismatch
int[] numbers = {10, 20, 30};
numbers[0] = "Hello";
Result:
- compilation error
Reason:
- an
int[]array can store only integer values
12.4 Null Reference
int[] numbers = null;
System.out.println(numbers.length);
Result:
- runtime exception:
NullPointerException
Reason:
- the variable does not refer to an actual array object
12.5 Invalid Size
int[] numbers = new int[-5];
Result:
- runtime exception:
NegativeArraySizeException
Reason:
- array size cannot be negative
13. Common Operations on Arrays
Foundational programs often perform these tasks:
- print all elements
- calculate the sum
- find the maximum or minimum value
- count specific values
- search for an element
Example: Sum of Array Elements
int[] numbers = {10, 20, 30, 40};
int sum = 0;
for (int number : numbers) {
sum += number;
}
System.out.println(sum); // 100
This pattern appears constantly in real programming and is worth mastering early.
14. Implementation Task
Task: Student Marks System
Create a Java program that:
- stores marks for multiple students in an array
- prints each mark
- calculates the total marks
- calculates the average
Reference Implementation
public class StudentMarksSystem {
public static void main(String[] args) {
int[] marks = {85, 90, 78, 92, 88};
int total = 0;
for (int i = 0; i < marks.length; i++) {
System.out.println("Mark " + (i + 1) + ": " + marks[i]);
total += marks[i];
}
double average = (double) total / marks.length;
System.out.println("Total: " + total);
System.out.println("Average: " + average);
}
}
Why This Task Matters
This task integrates several core ideas:
- array creation
- traversal
- arithmetic accumulation
- use of
length - numeric conversion for accurate average calculation
It is one of the first examples where a data structure and loop work together to solve a real problem.
15. Validation Checklist
Use this checklist before moving to the next chapter:
- the array is declared with the correct type
- values match the array element type
- indexes stay within valid bounds
- loops traverse the array correctly
lengthis used properly- the program compiles without errors
- the output matches the expected values
16. Knowledge Validation
Output Evaluation
Code:
int[] arr = {2, 4, 6};
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
Expected output:
2
4
6
Reason:
- the loop starts at index
0 - it continues up to
arr.length - 1 - each iteration prints one element
Edge Case
Code:
int[] arr = new int[3];
System.out.println(arr[0]);
Expected output:
0
Reason:
- arrays of primitive numeric types receive default value
0when created withnew
Concept Review
| Prompt | Correct Answer |
|---|---|
| Arrays store | Multiple values of the same type |
| First valid index | 0 |
| Last valid index | length - 1 |
| Array size after creation | Fixed |
| Array traversal usually uses | Loops |
17. Summary
This chapter introduced arrays as Java's first major data structure.
- arrays group related values under one variable name
- elements are accessed by zero-based indexes
- all elements share a common type
- array size is fixed after creation
- loops are the standard tool for traversal and processing
- arrays are reference types and behave accordingly in methods
Final Model
Array Variable -> Indexed Elements -> Traversal -> Processing -> Result
The central lesson is that arrays transform isolated values into structured data. They are the first step from single-variable programming toward real data processing and algorithmic thinking.
