OBJECT ORIENTED PROGRAMMING THROUGH JAVA : Unit - 3 : Topic - 1 : Arrays


1. Introduction to Arrays

Definition

An array in Java is a collection of variables of the same data type stored at contiguous memory locations. It allows us to store multiple values in a single variable, instead of declaring separate variables for each value.

  • Arrays are fixed-size (the size must be defined at the time of creation).

  • Each element in an array is accessed using an index.

  • Array indexing in Java starts from 0.

Why Arrays?

  • To handle large amounts of data efficiently.

  • Easy traversal using loops.

  • Better performance as elements are stored in continuous memory.


Key features of Arrays

Store Primitives and Objects: Java arrays can hold both primitive types (like int, char, boolean, etc.) and objects (like String, Integer, etc.)
Contiguous Memory Allocation When we use arrays of primitive types, the elements are stored in contiguous locations. For non primitive types, references of items are stored at contiguous locations.
Zero-based Indexing: The first element of the array is at index 0.
Fixed Length: After creating an array, its size is fixed; we can not change it.

Example (Without Array)

class WithoutArray { public static void main(String[] args) { int mark1 = 85, mark2 = 90, mark3 = 78, mark4 = 88, mark5 = 95; System.out.println("Marks: " + mark1 + ", " + mark2 + ", " + mark3 + ", " + mark4 + ", " + mark5); } }

➡️ Problem: Repetitive code, difficult to manage large data.


Example (With Array)

class WithArray { public static void main(String[] args) { int marks[] = {85, 90, 78, 88, 95}; // Array Declaration & Initialization System.out.println("Marks are:"); for(int i = 0; i < marks.length; i++) { System.out.println("Student " + (i+1) + ": " + marks[i]); } } }



2. Declaration and Initialization of Arrays

Array Declaration

In Java, arrays are objects, so they must be declared and created using the new keyword.

Syntax

datatype arrayName[]; // preferred datatype[] arrayName; // valid (alternative)

Array Creation

arrayName = new datatype[size];

Example

int numbers[]; // Declaration numbers = new int[5]; // Creation



Array Initialization

  • Method 1: Static Initialization (Direct values)

int numbers[] = {10, 20, 30, 40, 50};
  • Method 2: Dynamic Initialization (Assign values later)

int numbers[] = new int[5]; numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50;

Complete Example

class ArrayDemo { public static void main(String[] args) { // Static initialization int marks[] = {90, 80, 70, 60, 50}; // Dynamic initialization int numbers[] = new int[3]; numbers[0] = 100; numbers[1] = 200; numbers[2] = 300; System.out.println("Marks:"); for (int i = 0; i < marks.length; i++) { System.out.println(marks[i]); } System.out.println("\nNumbers:"); for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); } } }

3. Storage of Array in Computer Memory

How Arrays Are Stored in Memory

  1. Contiguous Memory Allocation

    • All array elements are stored next to each other in a continuous memory block.

    • This allows fast access using index.

  2. Array Indexing

    • Array index starts at 0.

    • Address of arr[i] is calculated as:

    Base Address + (i * Size_of_datatype)
  3. In Java (Special Case)

    • Arrays are objects in Java.

    • When we create an array using new, memory is allocated on the heap.

    • The variable (array name) stores a reference (address) to the memory location.

    • Example:

      int arr[] = new int[5];

      Here, arr holds a reference (address) pointing to 5 contiguous memory locations in the heap.


Diagram Representation

arr → | 10 | 20 | 30 | 40 | 50 | Index 0 1 2 3 4
  • Suppose arr[0] starts at address 1000 and each int takes 4 bytes:

    • arr[0] → Address 1000

    • arr[1] → Address 1004

    • arr[2] → Address 1008

    • arr[3] → Address 1012

    • arr[4] → Address 1016


Example Program to Show Memory Reference

class ArrayMemory { public static void main(String[] args) { int arr[] = {10, 20, 30}; System.out.println("Array reference: " + arr); // Prints memory reference System.out.println("First element: " + arr[0]); } }

Output (example):

Array reference: [I@15db9742 First element: 10

  • [I → Integer Array

  • @15db9742 → Hashcode representing memory location


4. Accessing Array Elements

Definition

Array elements in Java are accessed using their index number.

  • Indexing starts from 0 and ends at length - 1.

  • Accessing beyond the last index causes ArrayIndexOutOfBoundsException.


Syntax

arrayName[index];

Example

class AccessArray { public static void main(String[] args) { int numbers[] = {10, 20, 30, 40, 50}; // Access first and last element System.out.println("First Element: " + numbers[0]); System.out.println("Last Element: " + numbers[numbers.length - 1]); // Access using loop System.out.println("\nAll Elements:"); for (int i = 0; i < numbers.length; i++) { System.out.println("Index " + i + ": " + numbers[i]); } } }

Output:

First Element: 10 Last Element: 50 All Elements: Index 0: 10 Index 1: 20 Index 2: 30 Index 3: 40 Index 4: 50

5. Operations on Array Elements

Array elements can be used in operations like update, traverse, search, sort, and aggregate (sum/average).


1. Traversal

Visiting each element of the array.

for(int i = 0; i < arr.length; i++) { System.out.println(arr[i]); }

2. Updating Elements

Changing the value at a specific index.

arr[2] = 99; // updates 3rd element

3. Searching

Find a specific element by checking each value.

class SearchArray { public static void main(String[] args) { int arr[] = {10, 20, 30, 40, 50}; int key = 30; boolean found = false; for(int i = 0; i < arr.length; i++) { if(arr[i] == key) { System.out.println("Element " + key + " found at index " + i); found = true; break; } } if(!found) { System.out.println("Element not found!"); } } }

4. Sorting

Rearranging elements (ascending or descending).
(Using Arrays.sort() from java.util).

import java.util.Arrays; class SortArray { public static void main(String[] args) { int arr[] = {40, 10, 30, 50, 20}; Arrays.sort(arr); System.out.println("Sorted Array:"); for(int x : arr) { System.out.print(x + " "); } } }

5. Aggregate Operations (Sum, Average)

class SumAverage { public static void main(String[] args) { int arr[] = {10, 20, 30, 40, 50}; int sum = 0; for(int i = 0; i < arr.length; i++) { sum += arr[i]; } double avg = (double) sum / arr.length; System.out.println("Sum = " + sum); System.out.println("Average = " + avg); } }

6. Assigning Array to Another Array

In Java, arrays are objects. When you assign one array to another, only the reference (address) is copied, not the actual elements.


Example: Reference Assignment

class ArrayAssign { public static void main(String[] args) { int arr1[] = {10, 20, 30}; int arr2[] = arr1; // arr2 points to the same array as arr1 arr2[1] = 99; // change in arr2 also affects arr1 System.out.println("arr1 Elements:"); for(int x : arr1) { System.out.print(x + " "); } System.out.println("\narr2 Elements:"); for(int x : arr2) { System.out.print(x + " "); } } }

Output:

arr1 Elements: 10 99 30 arr2 Elements: 10 99 30

➡️ Both arr1 and arr2 point to the same memory location.


Creating a Copy of Array (Cloning)

To avoid reference sharing, use clone() or Arrays.copyOf().

Method 1: Using clone()

int arr1[] = {10, 20, 30}; int arr2[] = arr1.clone(); // creates new copy

Method 2: Using Arrays.copyOf()

import java.util.Arrays; int arr1[] = {10, 20, 30}; int arr2[] = Arrays.copyOf(arr1, arr1.length);

Method 3: Manual Copy

int arr1[] = {10, 20, 30}; int arr2[] = new int[arr1.length]; for(int i = 0; i < arr1.length; i++) { arr2[i] = arr1[i]; }


7. Dynamic Change of Array Size

Problem

  • Arrays in Java are fixed-size.

  • Once created, the size cannot be changed.

  • Example:

    int arr[] = new int[5]; // fixed at 5 elements

Solution

To change the size dynamically, we create a new array with the required size and copy the old elements into it.


Example: Manual Resizing

class DynamicArrayResize { public static void main(String[] args) { int arr[] = {10, 20, 30}; int newSize = 5; // Create new array int newArr[] = new int[newSize]; // Copy old elements for(int i = 0; i < arr.length; i++) { newArr[i] = arr[i]; } // Add new elements newArr[3] = 40; newArr[4] = 50; // Print resized array System.out.println("Resized Array:"); for(int x : newArr) { System.out.print(x + " "); } } }

Output:

Resized Array: 10 20 30 40 50

Using Arrays.copyOf()

Java provides an easier way:

import java.util.Arrays; class DynamicArray { public static void main(String[] args) { int arr[] = {1, 2, 3}; arr = Arrays.copyOf(arr, 6); // resize to 6 arr[3] = 4; arr[4] = 5; arr[5] = 6; System.out.println("Resized Array:"); for(int x : arr) { System.out.print(x + " "); } } }

Note

For truly dynamic arrays, Java provides ArrayList (in java.util), which automatically resizes itself.

8. Sorting Arrays

Sorting means arranging array elements in ascending or descending order.

Method 1: Manual Sorting (Bubble Sort Example)

class BubbleSort { public static void main(String[] args) { int arr[] = {50, 20, 40, 10, 30}; for(int i = 0; i < arr.length - 1; i++) { for(int j = 0; j < arr.length - i - 1; j++) { if(arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } System.out.println("Sorted Array:"); for(int x : arr) { System.out.print(x + " "); } } }

Output:

10 20 30 40 50

Method 2: Using Arrays.sort()

import java.util.Arrays; class SortExample { public static void main(String[] args) { int arr[] = {90, 10, 50, 30, 20}; Arrays.sort(arr); // ascending order System.out.println("Sorted Array:"); for(int x : arr) { System.out.print(x + " "); } } }

Output:

10 20 30 50 90

Method 3: Descending Order

import java.util.Arrays; import java.util.Collections; class SortDesc { public static void main(String[] args) { Integer arr[] = {90, 10, 50, 30, 20}; Arrays.sort(arr, Collections.reverseOrder()); System.out.println("Descending Order:"); for(int x : arr) { System.out.print(x + " "); } } }

Output:

90 50 30 20 10

9. Searching Values in Arrays

1. Linear Search

  • Checks each element one by one.

  • Works for both sorted and unsorted arrays.

  • Time Complexity: O(n)

class LinearSearch { public static void main(String[] args) { int arr[] = {10, 20, 30, 40, 50}; int key = 30; boolean found = false; for(int i = 0; i < arr.length; i++) { if(arr[i] == key) { System.out.println("Element found at index: " + i); found = true; break; } } if(!found) { System.out.println("Element not found"); } } }

2. Binary Search

  • Works only on sorted arrays.

  • Divides the array into halves to search.

  • Time Complexity: O(log n)

import java.util.Arrays; class BinarySearch { public static void main(String[] args) { int arr[] = {10, 20, 30, 40, 50}; int key = 40; int low = 0, high = arr.length - 1; boolean found = false; while(low <= high) { int mid = (low + high) / 2; if(arr[mid] == key) { System.out.println("Element found at index: " + mid); found = true; break; } else if(arr[mid] < key) { low = mid + 1; } else { high = mid - 1; } } if(!found) { System.out.println("Element not found"); } } }

3. Using Arrays.binarySearch()

import java.util.Arrays; class BinarySearchExample { public static void main(String[] args) { int arr[] = {10, 20, 30, 40, 50}; int index = Arrays.binarySearch(arr, 30); if(index >= 0) { System.out.println("Element found at index: " + index); } else { System.out.println("Element not found"); } } }


10. Class Arrays (Utility Class)

Definition

  • Arrays is a utility class in the package java.util.

  • It provides static methods to manipulate arrays: sorting, searching, comparing, filling, copying, etc.


Commonly Used Methods

MethodDescriptionExample
Arrays.sort(arr)Sorts array in ascending orderArrays.sort(numbers);
Arrays.sort(arr, Collections.reverseOrder())Sorts in descending orderArrays.sort(arr, Collections.reverseOrder());
Arrays.binarySearch(arr, key)Searches for an element in a sorted arrayArrays.binarySearch(arr, 20);
Arrays.copyOf(arr, newLength)Copies array to a new sizeArrays.copyOf(arr, 10);
Arrays.fill(arr, value)Fills entire array with a given valueArrays.fill(arr, 0);
Arrays.equals(arr1, arr2)Compares two arraysArrays.equals(a, b);
Arrays.toString(arr)Converts array to string formSystem.out.println(Arrays.toString(arr));

Example

import java.util.Arrays; class ArraysClassDemo { public static void main(String[] args) { int arr[] = {50, 10, 30, 20, 40}; Arrays.sort(arr); // sorting System.out.println("Sorted: " + Arrays.toString(arr)); int index = Arrays.binarySearch(arr, 30); // searching System.out.println("Index of 30: " + index); int copy[] = Arrays.copyOf(arr, 7); // resizing System.out.println("Copy: " + Arrays.toString(copy)); Arrays.fill(copy, 100); // filling System.out.println("Filled: " + Arrays.toString(copy)); } }

11. Two-Dimensional Arrays (2D Arrays)

Definition

  • A 2D array is an array of arrays, often used to represent matrices or tables.

  • Stored in row-major order in memory.

Declaration

datatype arrayName[][]; // Preferred datatype[][] arrayName; datatype[] arrayName[];

Creation

arrayName = new datatype[rows][columns];

Initialization

  • Static Initialization

int matrix[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };
  • Dynamic Initialization

int matrix[][] = new int[3][3]; matrix[0][0] = 1; matrix[0][1] = 2; matrix[0][2] = 3;

Accessing Elements

System.out.println(matrix[1][2]); // Row 1, Column 2

Example: Printing a 2D Array

class TwoDArray { public static void main(String[] args) { int matrix[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; System.out.println("Matrix:"); for(int i = 0; i < matrix.length; i++) { for(int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j] + " "); } System.out.println(); } } }

Output:

Matrix: 1 2 3 4 5 6 7 8 9

12. Arrays of Varying Lengths (Jagged Arrays)

Definition

  • A jagged array is a 2D array with rows of different lengths.

  • Unlike rectangular matrices, each row can have a different number of columns.


Declaration and Creation

int jagged[][] = new int[3][]; // 3 rows, column sizes not fixed jagged[0] = new int[2]; // 1st row has 2 columns jagged[1] = new int[4]; // 2nd row has 4 columns jagged[2] = new int[3]; // 3rd row has 3 columns

Initialization

jagged[0][0] = 10; jagged[0][1] = 20; jagged[1][0] = 30; jagged[1][1] = 40; jagged[1][2] = 50; jagged[1][3] = 60; jagged[2][0] = 70; jagged[2][1] = 80; jagged[2][2] = 90;

Example: Printing Jagged Array

class JaggedArray { public static void main(String[] args) { int jagged[][] = { {1, 2}, {3, 4, 5, 6}, {7, 8, 9} }; System.out.println("Jagged Array:"); for(int i = 0; i < jagged.length; i++) { for(int j = 0; j < jagged[i].length; j++) { System.out.print(jagged[i][j] + " "); } System.out.println(); } } }

Output:

Jagged Array: 1 2 3 4 5 6 7 8 9



13. Three-Dimensional Arrays

Definition

  • A three-dimensional (3D) array is an array of 2D arrays.

  • It can represent data in a cube-like structure (rows × columns × depth).

  • Useful in applications like image processing, 3D games, and simulations.


Declaration

datatype arrayName[][][];

Creation

arrayName = new datatype[x][y][z];
  • x → number of 2D matrices (depth/layers)

  • y → number of rows

  • z → number of columns


Static Initialization

int cube[][][] = { { {1, 2}, {3, 4} }, { {5, 6}, {7, 8} } };

Here:

  • cube[0][0][0] = 1

  • cube[1][1][1] = 8


Accessing Elements

System.out.println(cube[1][0][1]); // Output: 6

Example: Printing a 3D Array

class ThreeDArray { public static void main(String[] args) { int cube[][][] = { { {1, 2}, {3, 4} }, { {5, 6}, {7, 8} } }; System.out.println("3D Array Elements:"); for(int i = 0; i < cube.length; i++) { for(int j = 0; j < cube[i].length; j++) { for(int k = 0; k < cube[i][j].length; k++) { System.out.print(cube[i][j][k] + " "); } System.out.println(); } System.out.println("------"); } } }

Output:

3D Array Elements: 1 2 3 4 ------ 5 6 7 8 ------

14. Arrays as Vectors

Definition

  • A vector is a mathematical entity that has magnitude and direction.

  • In Java, arrays (especially 1D arrays) can represent vectors:

    • int[] v1 = {x1, y1, z1};

    • int[] v2 = {x2, y2, z2};


Common Vector Operations Using Arrays

1. Vector Addition

class VectorAddition { public static void main(String[] args) { int v1[] = {2, 4, 6}; int v2[] = {1, 3, 5}; int sum[] = new int[3]; for(int i = 0; i < v1.length; i++) { sum[i] = v1[i] + v2[i]; } System.out.print("Vector Sum: "); for(int x : sum) { System.out.print(x + " "); } } }

Output:

Vector Sum: 3 7 11

2. Scalar (Dot) Product

class DotProduct { public static void main(String[] args) { int v1[] = {2, 4, 6}; int v2[] = {1, 3, 5}; int dot = 0; for(int i = 0; i < v1.length; i++) { dot += v1[i] * v2[i]; } System.out.println("Dot Product = " + dot); } }

Output:

Dot Product = 44

3. Scalar Multiplication

class ScalarMultiplication { public static void main(String[] args) { int v[] = {2, 4, 6}; int scalar = 3; int result[] = new int[v.length]; for(int i = 0; i < v.length; i++) { result[i] = scalar * v[i]; } System.out.print("Scalar Multiplication: "); for(int x : result) { System.out.print(x + " "); } } }

Output:

Scalar Multiplication: 6 12 18

4. Magnitude of a Vector

v=v[0]2+v[1]2+v[2]2|v| = \sqrt{v[0]^2 + v[1]^2 + v[2]^2}
class VectorMagnitude { public static void main(String[] args) { int v[] = {3, 4, 12}; double sum = 0; for(int i = 0; i < v.length; i++) { sum += v[i] * v[i]; } double magnitude = Math.sqrt(sum); System.out.println("Magnitude = " + magnitude); } }

Output:

Magnitude = 13.0


Java Array Programs


Program 1: Accessing and Updating Array Elements

class AccessArray { public static void main(String[] args) { int arr[] = {10, 20, 30, 40, 50}; System.out.println("Original Array:"); for (int x : arr) System.out.print(x + " "); arr[2] = 99; // update 3rd element System.out.println("\nUpdated Array:"); for (int x : arr) System.out.print(x + " "); } }

Output

Original Array: 10 20 30 40 50 Updated Array: 10 20 99 40 50

Program 2: Dynamic Resizing of Array

import java.util.Arrays; class ResizeArray { public static void main(String[] args) { int arr[] = {1, 2, 3}; arr = Arrays.copyOf(arr, 6); // resize arr[3] = 4; arr[4] = 5; arr[5] = 6; System.out.println("Resized Array: " + Arrays.toString(arr)); } }

Output

Resized Array: [1, 2, 3, 4, 5, 6]

Program 3: Sorting and Searching

import java.util.Arrays; class SortSearch { public static void main(String[] args) { int arr[] = {50, 10, 40, 30, 20}; Arrays.sort(arr); // ascending System.out.println("Sorted: " + Arrays.toString(arr)); int index = Arrays.binarySearch(arr, 30); System.out.println("Element 30 found at index: " + index); } }

Output

Sorted: [10, 20, 30, 40, 50] Element 30 found at index: 2

Program 4: Two-Dimensional Array (Matrix Sum)

class TwoDArray { public static void main(String[] args) { int matrix[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; int sum = 0; System.out.println("Matrix:"); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.print(matrix[i][j] + " "); sum += matrix[i][j]; } System.out.println(); } System.out.println("Sum of elements = " + sum); } }

Output

Matrix: 1 2 3 4 5 6 7 8 9 Sum of elements = 45

Program 5: Jagged Array Example

class JaggedArray { public static void main(String[] args) { int jagged[][] = { {1, 2}, {3, 4, 5, 6}, {7, 8, 9} }; System.out.println("Jagged Array:"); for (int i = 0; i < jagged.length; i++) { for (int j = 0; j < jagged[i].length; j++) { System.out.print(jagged[i][j] + " "); } System.out.println(); } } }

Output

Jagged Array: 1 2 3 4 5 6 7 8 9

Program 6: Three-Dimensional Array

class ThreeDArray { public static void main(String[] args) { int cube[][][] = { { {1, 2}, {3, 4} }, { {5, 6}, {7, 8} } }; System.out.println("3D Array Elements:"); for (int i = 0; i < cube.length; i++) { for (int j = 0; j < cube[i].length; j++) { for (int k = 0; k < cube[i][j].length; k++) { System.out.print(cube[i][j][k] + " "); } System.out.println(); } System.out.println("------"); } } }

Output

3D Array Elements: 1 2 3 4 ------ 5 6 7 8 ------

Program 7: Array as Vectors (Addition & Dot Product)

class VectorOps { public static void main(String[] args) { int v1[] = {2, 4, 6}; int v2[] = {1, 3, 5}; // Addition int sum[] = new int[v1.length]; for (int i = 0; i < v1.length; i++) { sum[i] = v1[i] + v2[i]; } // Dot Product int dot = 0; for (int i = 0; i < v1.length; i++) { dot += v1[i] * v2[i]; } System.out.print("Vector Sum: "); for (int x : sum) System.out.print(x + " "); System.out.println("\nDot Product = " + dot); } }

Output

Vector Sum: 3 7 11 Dot Product = 44

Program 8: Assigning Arrays (Reference vs Clone)

import java.util.Arrays; class AssignArray { public static void main(String[] args) { int arr1[] = {10, 20, 30}; int arr2[] = arr1; // reference copy arr2[1] = 99; int arr3[] = arr1.clone(); // deep copy arr3[2] = 77; System.out.println("arr1 = " + Arrays.toString(arr1)); System.out.println("arr2 = " + Arrays.toString(arr2)); System.out.println("arr3 = " + Arrays.toString(arr3)); } }

Output

arr1 = [10, 99, 30] arr2 = [10, 99, 30] arr3 = [10, 99, 77]

Comments

Popular posts from this blog

Artificial Intelligence - UNIT - 1 Topic - 1 : Introduction to AI (Artificial Intelligence)

Career Guide - B.Tech Students

Financial Aid for Students: Scholarships from Government, NGOs & Companies