[go: up one dir, main page]

0% found this document useful (0 votes)
22 views10 pages

Arrays

The document provides a comprehensive overview of arrays in Java, including their declaration, creation, and access methods. It explains one-dimensional and two-dimensional arrays, their storage, initialization, and common operations like searching and sorting. Additionally, it discusses the advantages and disadvantages of using arrays, as well as their behavior as reference types in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views10 pages

Arrays

The document provides a comprehensive overview of arrays in Java, including their declaration, creation, and access methods. It explains one-dimensional and two-dimensional arrays, their storage, initialization, and common operations like searching and sorting. Additionally, it discusses the advantages and disadvantages of using arrays, as well as their behavior as reference types in Java.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Arrays

Arrays are very useful when multiple elements of the same data type need to be stored and
processed.

 Indices are the positions of array elements in square brackets.

 Indices designate the position of elements in the array.

 Arrays can be of different types: one-dimensional arrays or multi-dimensional arrays.

 A two-dimensional array is the simplest form of a multi-dimensional array.

 The simplest form of an array is a one-dimensional array.

 An array is given a name, and its elements are referred to by their indices.

 In Java, array indexing starts from 0.

 An array must be declared before it can be used to store information.

 An array definition specifies a variable type, a name, and its size to indicate how many
elements it will contain.

 The data type of an array element is known as the base type of the array.

 The array name specifies how the array will be referenced.

 The size of the array must be a positive integer or an integer constant.

An array must be declared and created before it can be used. This is a two-step process:

1. Declare a reference to an array.

2. Create the array using the new operator.

Java Syntax Example:

java

CopyEdit

// Declaring an array reference

int[] numbers;

// Creating an array of size 5

numbers = new int[5];

// Declaring and creating in a single line

int[] values = new int[10];

For example, double[] x; is used to create a reference to a double-type array. Then, x = new
double[5]; creates an array of five double values and stores its reference in x.
Accessing Array Elements

 An array element is accessed using the array name followed by an integer subscript (also
called an index) inside square brackets.

 In Java arrays, the element at position 1 has an index of 0, the element at position 2 has an
index of 1, and so on.

 The position of an element in the array is always index + 1.

Array Storage

Single-dimensional arrays are essentially lists of information of the same type, and their elements
are stored in contiguous memory locations in index order.

 The size or length of an array is determined using arrayName.length.

 Length is a property that returns the number of elements in the array.

 Internally, arrays are stored as special objects containing:

o A group of contiguous memory locations that all share the same name and data
type.

o A reference variable that stores the starting memory address of the array
elements.

o A separate instance variable storing the total number of elements in the array.

Java Syntax Example:

java

CopyEdit

// Declaring a reference to a double array

double[] x;

// Creating an array of size 5

x = new double[5];

// Accessing the length of the array

int size = x.length;

// Accessing an element

x[0] = 3.14;

System.out.println("First element: " + x[0]);

System.out.println("Array size: " + size);


When an array object is created using the new operator, its elements are automatically initialized
to:

 0 for numeric data types.

 false for boolean type.

 '\u0000' (the null character) for char type.

An array can also be initialized as:

java

CopyEdit

int[] A = {1, 2, 3, 4, 5};

Out-of-Bounds Access

 Subscripts other than 0 to n-1 (both inclusive) for an array with n elements are called out-
of-bound subscripts.

 A reference to an out-of-bound subscript results in an ArrayIndexOutOfBoundsException,


and the program will crash if the exception is not handled.

Two-Dimensional Arrays

A two-dimensional array is an array where each element is itself an array. It consists of rows and
columns:

 Rows are the horizontal portions.

 Columns are the vertical portions.

Syntax for Two-Dimensional Array Declaration in Java:

java

CopyEdit

// Declaring a two-dimensional array

dataType[][] arrayName;

// Creating a two-dimensional array with specific size

arrayName = new dataType[rows][columns];

// Declaring and initializing in one step

int[][] matrix = {

{1, 2, 3},

{4, 5, 6},
{7, 8, 9}

};

Storage Calculation for a Two-Dimensional Array

The amount of storage required to hold a two-dimensional array depends on:

1. The base type of the array.

2. The number of rows.

3. The number of columns.

The total memory required is calculated as:

mathematica

CopyEdit

Total Bytes = Number of Rows × Number of Columns × Size of Base Type

Searching in One-Dimensional Arrays

1. Linear Search

Linear search is a technique where each element of an array is compared with the search item one
by one until:

 The search item is found, or

 All elements have been compared.

Worst-case scenario: If the search item is one of the last elements, many comparisons will be
needed, making the process time-consuming.

2. Binary Search

Binary search is an efficient searching technique that works only for sorted arrays.

Steps:

1. Compare the search item with the middle element of the array.

2. If they match, the search is successful.

3. If the search item is less than the middle element (in ascending order), search in the first
half of the array.

4. Otherwise, search in the second half of the array.

Key Differences:

 Linear search works for both sorted and unsorted arrays.

 Binary search works only for sorted arrays and is faster than linear search.
Sorting in Arrays

Sorting means arranging array elements in ascending or descending order. Common sorting
techniques include:

 Bubble Sort

 Selection Sort

 Insertion Sort

 Merge Sort

 Quick Sort

Java Example for Linear and Binary Search

Linear Search Example

java

CopyEdit

class LinearSearch {

public static int search(int[] arr, int key) {

for (int i = 0; i < arr.length; i++) {

if (arr[i] == key) {

return i; // Found at index i

return -1; // Not found

public static void main(String[] args) {

int[] numbers = {10, 20, 30, 40, 50};

int key = 30;

int result = search(numbers, key);

System.out.println(result != -1 ? "Element found at index " + result : "Element not found");

Binary Search Example


java

CopyEdit

import java.util.Arrays;

class BinarySearch {

public static int search(int[] arr, int key) {

int left = 0, right = arr.length - 1;

while (left <= right) {

int mid = left + (right - left) / 2;

if (arr[mid] == key)

return mid;

if (arr[mid] < key)

left = mid + 1;

else

right = mid - 1;

return -1; // Not found

public static void main(String[] args) {

int[] numbers = {10, 20, 30, 40, 50};

int key = 30;

int result = search(numbers, key);

System.out.println(result != -1 ? "Element found at index " + result : "Element not found");

Selection Sort

The basic idea of selection sort is to repeatedly select the smallest key in the remaining unsorted
part of the array. Selection sort works by:

1. Finding the smallest (or largest) element in the array.


2. Moving it to its correct position.

3. Repeating the process for the next smallest (or largest) element.

After sorting:

 The smallest element is placed at index 0.

 The second smallest is placed at index 1, and so on.

Bubble Sort

The basic idea of bubble sort is to compare adjacent elements and swap them if they are not in the
correct order.

How it works:

 The largest element moves to the highest index position after each pass.

 This is achieved by repeatedly comparing two adjacent elements and swapping them if
needed.

 The process continues until the entire array is sorted.

Example: Sorting an array in ascending order using bubble sort moves the largest values to the
rightmost positions first.

Arrays vs. Objects in Java

Java arrays are objects, meaning they are reference types.

Important Consequences:

1. The == operator compares references (memory addresses), not the actual data stored in
arrays.

2. The .equals() method, when used with arrays, also compares references and not the data
inside the arrays.

Example in Java:

java

CopyEdit

int[] arr1 = {2, 3, 5, 7};

int[] arr2 = {2, 3, 5, 7};

System.out.println(arr1 == arr2); // false (different memory locations)

System.out.println(arr1.equals(arr2)); // false (compares references)


Java Example: Selection Sort & Bubble Sort

Selection Sort Implementation

java

CopyEdit

class SelectionSort {

public static void sort(int[] arr) {

int n = arr.length;

for (int i = 0; i < n - 1; i++) {

int minIndex = i;

for (int j = i + 1; j < n; j++) {

if (arr[j] < arr[minIndex]) {

minIndex = j;

// Swap the found minimum element with the first element

int temp = arr[minIndex];

arr[minIndex] = arr[i];

arr[i] = temp;

public static void main(String[] args) {

int[] arr = {64, 25, 12, 22, 11};

sort(arr);

for (int num : arr) {

System.out.print(num + " ");

Bubble Sort Implementation

java
CopyEdit

class BubbleSort {

public static void sort(int[] arr) {

int n = arr.length;

for (int i = 0; i < n - 1; i++) {

for (int j = 0; j < n - i - 1; j++) {

if (arr[j] > arr[j + 1]) {

// Swap

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

public static void main(String[] args) {

int[] arr = {64, 25, 12, 22, 11};

sort(arr);

for (int num : arr) {

System.out.print(num + " ");

Advantages of Arrays

1. Easy Declaration & Initialization – Can be done in a single line.

2. Efficient Memory Allocation – Predefined memory prevents runtime overheads.

3. Random Access – Any element can be accessed directly via index.

4. Fast Sequential Access – Contiguous storage ensures quick access.

5. Simplified Code – Easier management of multiple elements using a common name.


Disadvantages of Arrays

1. Fixed Size – Must be defined at the time of allocation.

2. Memory Management – Risk of memory wastage or shortage.

3. Not Suitable for Dynamic Needs – Cannot adjust memory size at runtime.

Consequences of Java Arrays as Reference Types

In Java, arrays are reference types, meaning they behave like objects. As a result, when you use an
assignment statement such as array1 = array2;, it copies the reference (memory address) from
array2 to array1. This means both array1 and array2 will refer to the same array object.

java

CopyEdit

int[] array1 = {2, 3, 5, 7};

int[] array2 = {2, 3, 5, 7, 11};

array1 = array2; // array1 now points to the same object as array2

array2[4] = 13;

System.out.println("array1[4] = " + array1[4]); // Prints: array1[4] = 13

Explanation:

 The assignment array1 = array2; makes array1 and array2 refer to the same object.

 Modifying array2[4] to 13 also modifies array1[4] since both reference the same array.

 Hence, array1[4] will print 13.

You might also like