Chapter 8: Arrays
1. What is an Array? (The Big Idea)
An array is a collection of elements of the same type stored in contiguous memory locations. You can think of it as a row of numbered lockers in a school corridor:
- Each locker can hold one item (of the same type)
- Each locker has a number (index) starting from 0
- You can access any locker quickly if you know its number
Real-life analogy: A row of 10 tiffin boxes on your dining table — all boxes are for food (same type), and you can say “give me the 3rd box” (index 2).
Key points:
- Fixed size (once created, you can’t change how many elements it holds — unlike ArrayList)
- All elements must be of the same data type
- Index starts at 0 and goes to length-1
- Arrays are reference types (they live on the heap)
2. Single-Dimensional Arrays (1D Arrays — The Most Common)
A. Declaring an Array
|
0 1 2 3 4 5 6 7 8 9 |
// Declaration (just saying "I want an array") int[] marks; // preferred style // or int marks[]; // also valid, but less common |
B. Creating an Array (Allocating Memory)
|
0 1 2 3 4 5 6 7 |
marks = new int[5]; // creates array of 5 integers // All elements get default value: 0 |
C. Declare + Create + Initialize in One Line
|
0 1 2 3 4 5 6 7 8 |
int[] marks = new int[5]; // 5 zeros: [0, 0, 0, 0, 0] int[] ages = {22, 25, 19, 30, 28}; // direct initialization String[] cities = {"Mumbai", "Delhi", "Bangalore", "Pune"}; |
Complete Example Program — Student Marks
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
public class ArrayDemo1 { public static void main(String[] args) { // 1. Create array with direct values int[] marks = {85, 92, 78, 95, 88}; // 2. Print length System.out.println("Number of students: " + marks.length); // 5 // 3. Access elements using index (0-based) System.out.println("First student's marks: " + marks[0]); // 85 System.out.println("Last student's marks: " + marks[4]); // 88 // System.out.println(marks[5]); // ERROR! ArrayIndexOutOfBoundsException // 4. Loop through array (classic for) System.out.println("\nAll marks:"); for (int i = 0; i < marks.length; i++) { System.out.println("Student " + (i+1) + ": " + marks[i]); } // 5. Enhanced for loop (for-each) System.out.println("\nUsing for-each:"); for (int score : marks) { System.out.print(score + " "); } } } |
Output:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Number of students: 5 First student's marks: 85 Last student's marks: 88 All marks: Student 1: 85 Student 2: 92 Student 3: 78 Student 4: 95 Student 5: 88 Using for-each: 85 92 78 95 88 |
3. Multi-Dimensional Arrays (2D Arrays — Like Tables/Matrices)
Think of a 2D array as a spreadsheet or chessboard — rows and columns.
Syntax:
|
0 1 2 3 4 5 6 7 |
int[][] matrix; // declaration matrix = new int[3][4]; // 3 rows, 4 columns → 12 elements |
Direct initialization:
|
0 1 2 3 4 5 6 7 8 9 10 |
int[][] marks = { {85, 92, 78, 95}, // row 0 {88, 76, 91, 82}, // row 1 {94, 89, 77, 93} // row 2 }; |
Accessing elements:
|
0 1 2 3 4 5 6 7 |
marks[0][2] // 78 (row 0, column 2) marks[2][3] // 93 (row 2, column 3) |
Complete Example — 2D Array (Student Marks in 3 Subjects)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
public class TwoDArrayDemo { public static void main(String[] args) { int[][] studentMarks = { {85, 92, 78}, // Student 1: Math, Science, English {88, 76, 91}, {94, 89, 77} }; // Print entire table System.out.println("Student Marks Table:"); for (int i = 0; i < studentMarks.length; i++) { // rows System.out.print("Student " + (i+1) + ": "); for (int j = 0; j < studentMarks[i].length; j++) { // columns System.out.print(studentMarks[i][j] + " "); } System.out.println(); } // Calculate average for each student System.out.println("\nAverage Marks:"); for (int i = 0; i < studentMarks.length; i++) { int sum = 0; for (int score : studentMarks[i]) { sum += score; } double avg = (double) sum / studentMarks[i].length; System.out.printf("Student %d average: %.2f\n", (i+1), avg); } } } |
Output:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Student Marks Table: Student 1: 85 92 78 Student 2: 88 76 91 Student 3: 94 89 77 Average Marks: Student 1 average: 85.00 Student 2 average: 85.00 Student 3 average: 86.67 |
4. Array Operations (Copy, Sort, Search)
A. Copying Arrays
Wrong way (shallow copy — same reference!):
|
0 1 2 3 4 5 6 7 8 9 |
int[] a = {1, 2, 3}; int[] b = a; // b and a point to SAME array b[0] = 99; System.out.println(a[0]); // 99 (changed!) |
Correct ways:
- Manual copy (loop)
|
0 1 2 3 4 5 6 7 8 9 |
int[] copy = new int[a.length]; for (int i = 0; i < a.length; i++) { copy[i] = a[i]; } |
- Arrays.copyOf() (recommended)
|
0 1 2 3 4 5 6 7 8 |
import java.util.Arrays; int[] copy = Arrays.copyOf(a, a.length); |
- System.arraycopy() (fastest for large arrays)
|
0 1 2 3 4 5 6 7 |
int[] copy = new int[a.length]; System.arraycopy(a, 0, copy, 0, a.length); |
B. Sorting Arrays
Use Arrays.sort() — very efficient!
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import java.util.Arrays; int[] numbers = {64, 34, 25, 12, 22, 11, 90}; System.out.println("Before: " + Arrays.toString(numbers)); Arrays.sort(numbers); System.out.println("After sort: " + Arrays.toString(numbers)); // Output: [11, 12, 22, 25, 34, 64, 90] |
For descending order (trick):
|
0 1 2 3 4 5 6 7 |
Integer[] nums = {64, 34, 25, 12}; // use Integer[] not int[] Arrays.sort(nums, Collections.reverseOrder()); |
C. Searching in Arrays
- Linear Search (simple, but slow for large arrays)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
int find = 25; boolean found = false; for (int i = 0; i < numbers.length; i++) { if (numbers[i] == find) { System.out.println("Found " + find + " at index " + i); found = true; break; } } |
- Binary Search (super fast — but array must be sorted!)
|
0 1 2 3 4 5 6 7 8 9 10 11 |
int index = Arrays.binarySearch(numbers, 25); if (index >= 0) { System.out.println("Found at index: " + index); } else { System.out.println("Not found"); } |
Quick Recap Table (Your Cheat Sheet)
| Feature | Syntax / Method | Notes / Example |
|---|---|---|
| 1D Array Declaration | int[] arr; or int arr[]; | Preferred: int[] |
| Create & Initialize | int[] arr = new int[5]; or {1,2,3} | Default: 0 for int, null for objects |
| Length | arr.length | No () — it’s a field! |
| Access | arr[0], arr[arr.length-1] | Index 0 to length-1 |
| 2D Array | int[][] matrix = new int[3][4]; | matrix[row][col] |
| Copy (safe) | Arrays.copyOf(arr, arr.length) | Or System.arraycopy() |
| Sort | Arrays.sort(arr) | Ascending by default |
| Binary Search | Arrays.binarySearch(arr, value) | Array must be sorted! Returns index or <0 |
Common Mistakes & Fixes
| Mistake | Problem | Fix |
|---|---|---|
| int[] arr = new int[5] then arr[5] | ArrayIndexOutOfBoundsException | Max index = length-1 |
| int[] a = b; then modify a | Both arrays change (same reference) | Use Arrays.copyOf() |
| Arrays.sort() on unsorted for binarySearch | Wrong results | Sort first! |
| String[] names = new String[3]; then print without init | Prints null null null | Initialize: names[0] = “Webliance”; |
| Forgetting import java.util.Arrays; | Cannot find symbol for sort/copyOf | Import it! |
Homework for You (Practice to Master!)
- Basic: Create an array of 7 days of the week. Print them using for-each loop.
- Medium: Take 5 numbers from user → store in array → find min, max, sum, average.
- Advanced: Create 2D array 4×4 → fill with random numbers 1–100 → print matrix → find sum of each row & column.
- Fun: Create array of your favorite 5 movies → sort them alphabetically → print.
- Challenge: Write linear search and binary search methods — compare how many comparisons each makes for a large array.
You’re doing amazing! Arrays are the foundation for so many things — lists, matrices, data processing, games, etc.
