0% found this document useful (0 votes)
20 views40 pages

Arrays

An array is a fixed-size collection of homogeneous elements stored in contiguous memory locations, allowing for efficient access via indices. Key operations include accessing, modifying, iterating, and performing computations on array elements, as well as copying and resizing arrays. For dynamic resizing, Java provides ArrayList, which automatically adjusts its size as elements are added or removed.

Uploaded by

venkatsatish287
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views40 pages

Arrays

An array is a fixed-size collection of homogeneous elements stored in contiguous memory locations, allowing for efficient access via indices. Key operations include accessing, modifying, iterating, and performing computations on array elements, as well as copying and resizing arrays. For dynamic resizing, Java provides ArrayList, which automatically adjusts its size as elements are added or removed.

Uploaded by

venkatsatish287
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

ARRAYS

An array is a collection of elements, all of which are of the same type (such as
integers, characters, or objects). These elements are stored in contiguous memory
locations and can be accessed using an index.
Key Characteristics of Arrays:
1. Fixed Size: The size of an array is determined when it is created and cannot be
changed. For example, if you create an array with a size of 10, it will always
hold 10 elements.
2. Index-Based Access: Elements in an array are accessed using indices. Indices
typically start from 0. For example, in a 5-element array, the first element is
accessed with index 0, the second with index 1, and so on.
3. Homogeneous Elements: All elements in an array are of the same type, which
allows for efficient storage and retrieval.
Advantages of Arrays:
1. Efficient Memory Usage: Arrays use a contiguous block of memory, which
can be more efficient than other data structures.
2. Fast Access: Accessing elements by index is very fast, with a time complexity
of O(1).
Limitations of Arrays:
1. Fixed Size: Once an array is created, its size cannot be changed. This can lead
to wasted space or insufficient space if the size estimate is incorrect.
2. Homogeneous Elements: Arrays only store elements of the same type, which
can be limiting.

DECLARATION AND INITIALIZATION:


Declaration is the process of specifying the type and the name of the array. It tells the
compiler or interpreter what kind of array you want to use but does not allocate
memory or set initial values.
In Java:
int [] numbers; // Declaration of an array of integers
In this line, int[] specifies that numbers is an array of integers, but no memory is
allocated yet, and no values are set.
Initialization is the process of assigning values to the elements of the array after it has
been declared. You can either initialize an array at the time of declaration or
separately.
In Java:
You can initialize an array at the time of declaration:
int[] numbers = {1, 2, 3, 4, 5}; // Declaration and initialization
(Or)
you can declare and then initialize:
int[] numbers = new int[5]; // Declaration and allocation
numbers[0] = 1; // Initialization
numbers[1] = 2; // Initialization
STORAGE OF AN ARRAY IN COMPUTER MEMORY:
Arrays are stored in computer memory in a structured and efficient manner, which
allows for quick access to their elements. Understanding how arrays are stored helps
in grasping their performance characteristics and memory usage. Here’s a detailed
explanation of how arrays are stored in computer memory:
1. Contiguous Memory Allocation
Arrays are typically stored in contiguous blocks of memory. This means that all
elements of an array are placed one after the other in sequential memory locations.
This contiguous allocation allows for fast indexing and access to array elements.
For example, consider an array of integers in a language like C or Java. If the array
has 5 elements and each integer occupies 4 bytes of memory, the array will occupy 20
bytes in total, with each integer placed in consecutive memory addresses.
2. Memory Layout
Here’s a breakdown of how an array is laid out in memory:
 Base Address: The address of the first element of the array. It’s the starting
point from which all other elements are accessed.
 Element Size: The size of each element in the array. For example, an int might
be 4 bytes, a char 1 byte, etc.
 Index Calculation: To access a specific element, the array’s base address is
used along with the index and the size of each element to compute the exact
memory address. For an array A of type int with a base address base and index
i, the memory address of the element at index i is:
Address of A[i]= base + (i × size of each element)
3. Example
Array Declaration:
int numbers[4] = {10, 20, 30, 40};
Memory Layout: Assume:
 base_address = 1000
 Size of int = 4 bytes
The memory layout might look like this:
 numbers[0] at address 1000: 10
 numbers[1] at address 1004: 20
 numbers[2] at address 1008: 30
 numbers[3] at address 1012: 40
Access Calculation: To access numbers[2], you compute:

4. Advantages of Contiguous Allocation


 Fast Access: Direct access to elements via index calculation is very quick, with
a time complexity of O(1) because it involves simple arithmetic operations.
 Cache Efficiency: Contiguous memory allocation improves cache performance
as accessing consecutive elements is more likely to be cached by the CPU.
5. Limitations
 Fixed Size: Once an array’s size is set, it cannot be changed, which might lead
to inefficiencies if the array is too large or too small.
 Memory Waste: If the array size is not used fully, the allocated memory might
be wasted.

Accessing Elements of an array:


To access elements in an array, you use the array name followed by the index of the
element you want to access in square brackets [].
Example:
// Accessing the first element (index 0)
int firstNumber = numbers[0]; // 1 in this case

// Accessing the third element (index 2)


int thirdNumber = numbers[2]; // 3 in this case

OPERATIONS ON ARRAY:
Operations on array elements in Java encompass a variety of tasks, including
accessing, modifying, iterating, and performing computations. Here’s a detailed look
at these operations:
1. Accessing Array Elements
Accessing elements in an array involves using the index to retrieve the value stored at
that position.
java
Copy code
int[] numbers = {10, 20, 30, 40, 50};
int firstElement = numbers[0]; // Accesses the first element (10)
int secondElement = numbers[1]; // Accesses the second element (20)
2. Modifying Array Elements
You can change the value of an array element by assigning a new value to a specific
index.
int[] numbers = {10, 20, 30, 40, 50};
numbers[2] = 35; // Modifies the third element to 35
3. Iterating Over Array Elements
To perform operations on each element, you typically use loops. Common loop types
include the for loop and the enhanced for loop.
Using a for Loop:
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]); // Prints each element
}
Using an Enhanced for Loop:
int[] numbers = {10, 20, 30, 40, 50};
for (int number : numbers) {
System.out.println(number); // Prints each element
}
4. Computing Values Based on Array Elements
You can perform various computations using array elements, such as summing values,
finding the maximum or minimum, or calculating the average.
Sum of Array Elements:
java
Copy code
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;
for (int number : numbers) {
sum += number; // Accumulate sum
}
System.out.println("Sum: " + sum); // Output: Sum: 150
Finding the Maximum Value:
java
Copy code
int[] numbers = {10, 20, 30, 40, 50};
int max = numbers[0];
for (int number : numbers) {
if (number > max) {
max = number; // Update max if current number is greater
}
}
System.out.println("Max: " + max); // Output: Max: 50
Finding the Minimum Value:
java
Copy code
int[] numbers = {10, 20, 30, 40, 50};
int min = numbers[0];
for (int number : numbers) {
if (number < min) {
min = number; // Update min if current number is smaller
}
}
System.out.println("Min: " + min); // Output: Min: 10
Calculating the Average:
java
Copy code
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;
for (int number : numbers) {
sum += number;
}
double average = (double) sum / numbers.length;
System.out.println("Average: " + average); // Output: Average: 30.0
5. Searching for an Element
To find a specific element in the array, you can iterate through the array and check
each value.
Linear Search:
int[] numbers = {10, 20, 30, 40, 50};
int target = 30;
boolean found = false;
for (int number : numbers) {
if (number == target) {
found = true;
break; // Exit the loop once the element is found
}
}
System.out.println("Element found: " + found); // Output: Element found: true
6. Sorting and Copying Arrays
Java provides utility methods for sorting and copying arrays.
Sorting an Array:
java
Copy code
import java.util.Arrays;

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


Arrays.sort(numbers); // Sorts the array in ascending order
System.out.println(Arrays.toString(numbers)); // Output: [10, 20, 30, 40, 50]
Copying an Array:
java
Copy code
int[] numbers = {10, 20, 30, 40, 50};
int[] copy = Arrays.copyOf(numbers, numbers.length); // Copies the entire array
System.out.println(Arrays.toString(copy)); // Output: [10, 20, 30, 40, 50]
Summary
 Accessing Elements: Use indices to retrieve values.
 Modifying Elements: Assign new values to specific indices.
 Iterating: Use loops to process each element.
 Computations: Perform operations like sum, max, min, and average.
 Searching: Use linear search for finding elements.
 Sorting and Copying: Use utility methods for sorting and copying arrays

AAAIGNING ONE ARRAY TO ANOTHER:


assigning one array to another involves different approaches depending on whether
you want to create a reference to the original array or make a copy of it. Here’s a
detailed look at both scenarios:
1. Assigning a Reference to Another Array
When you assign one array to another, you’re actually copying the reference, not the
contents of the array. This means both variables will refer to the same array in
memory.
Example:
int[] originalArray = {1, 2, 3, 4, 5};
int[] referenceArray = originalArray; // referenceArray points to the same array as
originalArray

// Modifying referenceArray will also modify originalArray


referenceArray[0] = 10;

System.out.println("originalArray[0]: " + originalArray[0]); // Output: 10


System.out.println("referenceArray[0]: " + referenceArray[0]); // Output: 10
2. Creating a Copy of an Array
If you want to create a new array with the same contents but independent of the
original array, you need to copy the array. There are several ways to copy arrays in
Java:
Using System.arraycopy()
The System.arraycopy() method is a standard way to copy a portion or all of an array.
EX:
int[] originalArray = {1, 2, 3, 4, 5};
int[] copyArray = new int[originalArray.length]; // Create a new array with the same
length

// Copy elements from originalArray to copyArray


System.arraycopy(originalArray, 0, copyArray, 0, originalArray.length);

copyArray[0] = 10; // Modify copyArray

System.out.println("originalArray[0]: " + originalArray[0]); // Output: 1


System.out.println("copyArray[0]: " + copyArray[0]); // Output: 10
Using Arrays.copyOf()
The Arrays.copyOf() method from the java.util.Arrays class creates a new array and
copies the specified number of elements from the original array.
EX:
import java.util.Arrays;

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


int[] copyArray = Arrays.copyOf(originalArray, originalArray.length); // Copy the
entire array

copyArray[0] = 10; // Modify copyArray

System.out.println("originalArray[0]: " + originalArray[0]); // Output: 1


System.out.println("copyArray[0]: " + copyArray[0]); // Output: 10
Using clone()

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


int[] copyArray = originalArray.clone(); // Create a copy of the array

copyArray[0] = 10; // Modify copyArray

System.out.println("originalArray[0]: " + originalArray[0]); // Output: 1


System.out.println("copyArray[0]: " + copyArray[0]); // Output: 10
Summary
 Reference Assignment: Assigning one array to another just copies the
reference, not the actual content.
 Copying Arrays:
o System.arraycopy(): Efficient for copying parts or all of an array.
o Arrays.copyOf(): Convenient for creating a copy with the same length
or a specific number of elements.
o clone(): Simple way to create a copy of the entire array.

DYNAMIC CHANGE OF ARRAY SIZE:

arrays are fixed in size once they are created. This means that you cannot directly
change the size of an existing array. However, you can achieve a dynamic change in
array size by creating a new array and copying the elements from the old array to the
new one. Java provides several methods and classes that can help you manage
dynamically sized collections of elements. Here’s how you can handle dynamic
resizing of arrays in Java:
1. Manually Resizing an Array
To manually resize an array, you need to:
1. Create a New Array: Create a new array with the desired size.
2. Copy Elements: Copy elements from the old array to the new one.
3. Replace the Old Array: Optionally, you can reassign the reference to the new
array.
Example:
Suppose you want to resize an array to accommodate more elements:
java
Copy code
public class ArrayResizeExample {
public static void main(String[] args) {
int[] oldArray = {1, 2, 3, 4, 5}; // Original array
int newSize = 10; // New size
int[] newArray = new int[newSize]; // Create a new array with the new size

// Copy elements from oldArray to newArray


System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);

// Fill in the new elements (optional)


for (int i = oldArray.length; i < newSize; i++) {
newArray[i] = i + 1; // Example of filling new elements
}

// Print the new array


for (int value : newArray) {
System.out.print(value + " "); // Output: 1 2 3 4 5 6 7 8 9 10
}
}
}
2. Using ArrayList for Dynamic Resizing
For more flexibility and automatic resizing, you can use the ArrayList class from the
Java Collections Framework. ArrayList is a dynamically sized array-like data structure
that automatically handles resizing.
Basic Operations with ArrayList:
1. Creating an ArrayList:
java
Copy code
import java.util.ArrayList;

ArrayList<Integer> list = new ArrayList<>();


2. Adding Elements:
java
Copy code
list.add(1);
list.add(2);
list.add(3);
3. Accessing Elements:
java
Copy code
int firstElement = list.get(0); // Retrieves the first element
4. Modifying Elements:
java
Copy code
list.set(1, 20); // Sets the element at index 1 to 20
5. Removing Elements:
java
Copy code
list.remove(2); // Removes the element at index 2
6. Resizing: The ArrayList automatically resizes as needed when you add or
remove elements.
Example:
java
Copy code
import java.util.ArrayList;

public class ArrayListExample {


public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();

// Adding elements
list.add(1);
list.add(2);
list.add(3);

// Modifying elements
list.set(1, 20);

// Removing an element
list.remove(0);

// Print the ArrayList


for (int value : list) {
System.out.print(value + " "); // Output: 20 3
}
}
}
3. Using Other Collections
In addition to ArrayList, other collections like LinkedList and Vector can also be used
for dynamic resizing and offer various advantages based on your specific needs.
 LinkedList: Provides efficient insertions and deletions at both ends.
 Vector: Similar to ArrayList but synchronized, making it thread-safe.
Summary
 Fixed Arrays: Arrays in Java are of fixed size once created. To resize, you
must create a new array and copy the elements.
 Dynamic Arrays with ArrayList: For dynamic resizing, use ArrayList, which
handles resizing internally and provides various methods for manipulation.
 Other Collections: Consider other Java collections based on performance and
feature requirements.
Using ArrayList or other collections provides more flexibility and ease of use
compared to manually resizing arrays, especially in situations where the size of the
collection may frequently change.

SORTING OF ARRAYS :
Sorting arrays in Java involves arranging elements in a specific order, such as
ascending or descending. Java provides various methods to sort arrays, and the choice
of method depends on the type of array and specific requirements.
Basic Sorting Using Arrays.sort()
The Arrays class in Java, part of the java.util package, provides a convenient method
called sort() for sorting arrays. This method uses a dual-pivot quicksort algorithm for
primitive types (like int, char, etc.) and a modified mergesort algorithm for objects.
Sorting Primitive Arrays
For primitive types, such as int, double, char, etc.,

import java.util.Arrays;

public class Main {


public static void main(String[] args) {
int[] numbers = {5, 2, 8, 1, 3};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // Output: [1, 2, 3, 5, 8]
}
}
Sorting Object Arrays
For arrays of objects (like String or custom objects), Arrays.sort() will use a variant of
mergesort which is stable (preserves the order of equal elements).

import java.util.Arrays;

public class Main {


public static void main(String[] args) {
String[] words = {"banana", "apple", "orange"};
Arrays.sort(words);
System.out.println(Arrays.toString(words)); // Output: [apple, banana, orange]
}
}
Custom Sorting with Comparators
If you need custom sorting (e.g., sorting in descending order), you can use the
Comparator interface with the Arrays.sort() method. This is particularly useful for
object arrays.
import java.util.Arrays;
import java.util.Comparator;

public class Main {


public static void main(String[] args) {
Integer[] numbers = {5, 2, 8, 1, 3};
Arrays.sort(numbers, Comparator.reverseOrder());
System.out.println(Arrays.toString(numbers)); // Output: [8, 5, 3, 2, 1]
}
}
SEARCHING FOR ELEMENTS IN ARRAYS:
Searching for values in arrays in Java can be done in several ways, depending on
whether the array is sorted or unsorted and the specific requirements of the search.
Here’s a detailed explanation of different search methods:
1. Linear Search
Linear Search is a straightforward algorithm where you iterate through each element
of the array until you find the target value or reach the end of the array.
Example:
public class LinearSearchExample {
public static void main(String[] args) {
int[] numbers = {3, 7, 1, 9, 5};
int target = 9;
int index = linearSearch(numbers, target);

if (index != -1) {
System.out.println("Found target at index: " + index);
} else {
System.out.println("Target not found.");
}
}

public static int linearSearch(int[] array, int target) {


for (int i = 0; i < array.length; i++) {
if (array[i] == target) {
return i;
}
}
return -1; // Target not found
}
}
2. Binary Search
Binary Search is more efficient than linear search but requires the array to be sorted.
It works by repeatedly dividing the search interval in half. If the value of the target is
less than the value in the middle, it narrows the search to the lower half. Otherwise, it
narrows it to the upper half.
Example:
import java.util.Arrays;

public class BinarySearchExample {


public static void main(String[] args) {
int[] numbers = {1, 3, 5, 7, 9};
int target = 7;
int index = Arrays.binarySearch(numbers, target);

if (index >= 0) {
System.out.println("Found target at index: " + index);
} else {
System.out.println("Target not found.");
}
}
}
3. Searching for Objects
For arrays of objects, such as String or custom classes, you typically use the
Arrays.binarySearch() method if the array is sorted, or perform a linear search if it’s
not.

Example with Strings:


import java.util.Arrays;

public class StringSearchExample {


public static void main(String[] args) {
String[] words = {"apple", "banana", "cherry"};
String target = "banana";

// Ensure the array is sorted before binary search


Arrays.sort(words);
int index = Arrays.binarySearch(words, target);

if (index >= 0) {
System.out.println("Found target at index: " + index);
} else {
System.out.println("Target not found.");
}
}
}

ARRAYS CLASS:
The Arrays class in Java is a utility class in the java.util package that provides a range
of static methods to manipulate arrays. This class simplifies many common operations
you need to perform on arrays, such as sorting, searching, and copying. Here’s an
overview of some of the key methods and functionalities provided by the Arrays class:
1. Sorting Arrays
 Arrays.sort(): Sorts the elements of the array in ascending order. It works for
both primitive types and object types.
Example:
import java.util.Arrays;

public class SortExample {


public static void main(String[] args) {
int[] numbers = {5, 2, 8, 1, 3};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // Output: [1, 2, 3, 5, 8]
}
}
For objects, it uses the compareTo method or a provided Comparator to determine the
order.
Example with Objects:
import java.util.Arrays;
import java.util.Comparator;

class Person {
String name;
int age;

Person(String name, int age) {


this.name = name;
this.age = age;
}

@Override
public String toString() {
return name + " (" + age + ")";
}
}

public class SortObjectsExample {


public static void main(String[] args) {
Person[] people = {
new Person("Alice", 30),
new Person("Bob", 25),
new Person("Charlie", 35)
};

// Sort by age
Arrays.sort(people, Comparator.comparingInt(p -> p.age));
System.out.println(Arrays.toString(people)); // Output: [Bob (25), Alice (30),
Charlie (35)]
}
}
2. Searching Arrays
 Arrays.binarySearch(): Searches for a specific value in a sorted array using
binary search. It returns the index of the value if found; otherwise, it returns a
negative number.
Example:
import java.util.Arrays;

public class SearchExample {


public static void main(String[] args) {
int[] numbers = {1, 2, 3, 5, 8};
int index = Arrays.binarySearch(numbers, 5);
System.out.println("Index of 5: " + index); // Output: Index of 5: 3
}
}
3. Copying Arrays
 Arrays.copyOf(): Creates a new array with a copy of the specified range of the
original array.
Example:
import java.util.Arrays;
public class CopyExample {
public static void main(String[] args) {
int[] original = {1, 2, 3, 4, 5};
int[] copy = Arrays.copyOf(original, 3);
System.out.println(Arrays.toString(copy)); // Output: [1, 2, 3]
}
}
 Arrays.copyOfRange(): Copies a range of elements from the original array.
Example:
import java.util.Arrays;

public class CopyRangeExample {


public static void main(String[] args) {
int[] original = {1, 2, 3, 4, 5};
int[] copy = Arrays.copyOfRange(original, 1, 4);
System.out.println(Arrays.toString(copy)); // Output: [2, 3, 4]
}
}
4. Filling Arrays
 Arrays.fill(): Assigns a specified value to all elements of the array.
Example:
import java.util.Arrays;

public class FillExample {


public static void main(String[] args) {
int[] numbers = new int[5];
Arrays.fill(numbers, 7);
System.out.println(Arrays.toString(numbers)); // Output: [7, 7, 7, 7, 7]
}
}
5. Comparing Arrays
 Arrays.equals(): Compares two arrays for equality. It returns true if the arrays
have the same length and corresponding elements are equal.
Example:
import java.util.Arrays;

public class EqualsExample {


public static void main(String[] args) {
int[] array1 = {1, 2, 3};
int[] array2 = {1, 2, 3};
System.out.println(Arrays.equals(array1, array2)); // Output: true
}
}
6. Converting Arrays to Strings
 Arrays.toString(): Converts a single-dimensional array to a string
representation.
Example:
import java.util.Arrays;

public class ToStringExample {


public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(numbers)); // Output: [1, 2, 3, 4, 5]
}
}
 Arrays.deepToString(): Converts multidimensional arrays to a string
representation.
Example:
import java.util.Arrays;

public class DeepToStringExample {


public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(Arrays.deepToString(matrix)); // Output: [[1, 2, 3], [4, 5, 6]]
}
}
Summary
The Arrays class provides a powerful set of static methods for array manipulation,
including:
 Sorting: Arrays.sort()
 Searching: Arrays.binarySearch()
 Copying: Arrays.copyOf(), Arrays.copyOfRange()
 Filling: Arrays.fill()
 Comparing: Arrays.equals()
 Converting to String: Arrays.toString(), Arrays.deepToString()

2D ARRAYS:
a two-dimensional array (often referred to as a 2D array) is essentially an array of
arrays. It allows you to store data in a tabular form, resembling a matrix or grid. Each
element in a 2D array is accessed using two indices: one for the row and one for the
column.
Declaring and Initializing a 2D Array
Declaration
To declare a 2D array in Java, you specify the type of the elements followed by two
sets of square brackets:
int[][] matrix;
Initialization
You can initialize a 2D array in several ways:
1. Static Initialization
If you know the values at compile time, you can initialize the array with values
directly:

int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
2. Dynamic Initialization
You can create a 2D array and then initialize it:

int[][] matrix = new int[3][3]; // Creates a 3x3 array

// Initialize elements
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[1][0] = 4;
matrix[1][1] = 5;
matrix[1][2] = 6;
matrix[2][0] = 7;
matrix[2][1] = 8;
matrix[2][2] = 9;
You can also initialize with different lengths for each row:
int[][] matrix = new int[3][];
matrix[0] = new int[2]; // First row with 2 columns
matrix[1] = new int[3]; // Second row with 3 columns
matrix[2] = new int[1]; // Third row with 1 column

// Assign values
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[1][0] = 3;
matrix[1][1] = 4;
matrix[1][2] = 5;
matrix[2][0] = 6;
Accessing Elements
Elements in a 2D array are accessed using two indices: one for the row and one for the
column.
java
Copy code
int value = matrix[1][2]; // Accesses the element at row 1, column 2
Iterating Over a 2D Array
You can use nested loops to iterate over a 2D array:

Example:

public class TwoDArrayExample {


public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Iterate over rows


for (int i = 0; i < matrix.length; i++) {
// Iterate over columns
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}
Common Operations
1. Finding the Size
You can get the number of rows and columns using the length attribute:

int numRows = matrix.length; // Number of rows


int numCols = matrix[0].length; // Number of columns in the first row
2. Copying a 2D Array
To copy a 2D array, you can use a nested loop or leverage System.arraycopy() for
efficiency:
java
Copy code
int[][] copy = new int[matrix.length][];
for (int i = 0; i < matrix.length; i++) {
copy[i] = matrix[i].clone(); // Copies each row
}
3. Flattening a 2D Array
If you need a one-dimensional representation of a 2D array:
int[] flat = new int[matrix.length * matrix[0].length];
int index = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
flat[index++] = matrix[i][j];
}
}
Summary
 Declaration: int[][] matrix;
 Initialization: Both static (predefined values) and dynamic (values set later)
methods are supported.
 Accessing: Use [row][column] to get or set values.
 Iteration: Use nested loops to traverse elements.
 Operations: Includes finding sizes, copying, and flattening.

ARRAYS OF VARYING LENGTHS:


you can create arrays with varying lengths, often referred to as "jagged arrays" or
"array of arrays." Unlike a rectangular 2D array where every row has the same
number of columns, a jagged array allows each row (or sub-array) to have a different
length. This provides flexibility when dealing with data that doesn’t fit neatly into a
rectangular grid.

Declaring and Initializing Jagged Arrays


Declaration
To declare a jagged array, you create an array where each element is itself an array.
The outer array holds references to these inner arrays.

int[][] jaggedArray;
Initialization
You can initialize a jagged array by first creating the outer array and then initializing
each inner array separately.

public class JaggedArrayExample {


public static void main(String[] args) {
// Declare and initialize the jagged array
int[][] jaggedArray = new int[3][]; // 3 rows, but column sizes are not specified yet

// Initialize each row with different lengths


jaggedArray[0] = new int[2]; // First row with 2 columns
jaggedArray[1] = new int[3]; // Second row with 3 columns
jaggedArray[2] = new int[1]; // Third row with 1 column

// Assign values
jaggedArray[0][0] = 1;
jaggedArray[0][1] = 2;
jaggedArray[1][0] = 3;
jaggedArray[1][1] = 4;
jaggedArray[1][2] = 5;
jaggedArray[2][0] = 6;

// Print the jagged array


for (int i = 0; i < jaggedArray.length; i++) {
for (int j = 0; j < jaggedArray[i].length; j++) {
System.out.print(jaggedArray[i][j] + " ");
}
System.out.println();
}
}
}
Accessing Elements
You access elements in a jagged array using two indices: the first index refers to the
row, and the second index refers to the column within that row.

int value = jaggedArray[1][2]; // Accesses the element in the second row, third column

Iterating Over a Jagged Array


Iterating through a jagged array involves nested loops. The outer loop iterates over
each row, while the inner loop iterates over each column of the current row.

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


for (int j = 0; j < jaggedArray[i].length; j++) {
System.out.print(jaggedArray[i][j] + " ");
}
System.out.println();
}
Common Operations
1. Finding the Size
o Number of Rows: Use jaggedArray.length.
o Number of Columns in a Specific Row: Use
jaggedArray[rowIndex].length.

int numRows = jaggedArray.length; // Number of rows


int numColsInRow1 = jaggedArray[0].length; // Number of columns in the first row
2. Resizing Rows
You can dynamically resize individual rows (inner arrays), but not the outer array
(number of rows):

jaggedArray[0] = new int[5]; // Resizing the first row to have 5 columns

3. Copying Jagged Arrays


Copying a jagged array involves copying each inner array separately:

int[][] copy = new int[jaggedArray.length][];


for (int i = 0; i < jaggedArray.length; i++) {
copy[i] = jaggedArray[i].clone(); // Copies each row
}
4. Flattening a Jagged Array
If you need a one-dimensional representation of a jagged array:

int totalLength = 0;
for (int[] row : jaggedArray) {
totalLength += row.length;
}

int[] flat = new int[totalLength];


int index = 0;
for (int[] row : jaggedArray) {
for (int element : row) {
flat[index++] = element;
}
}
Advantages of Jagged Arrays
1. Flexibility: Each row can have a different length, which is useful when dealing
with data that doesn’t fit neatly into a rectangular grid.
2. Memory Efficiency: Memory is allocated only for the required size of each
row, which can be more efficient than using a rectangular array with a fixed
number of columns.
Summary
 Declaration: int[][] jaggedArray;
 Initialization: Initialize the outer array and then each inner array separately.
 Access: Use [row][column] to get or set values.
 Iteration: Use nested loops to traverse the array.
 Operations: Includes finding sizes, resizing rows, copying, and flattening.

3D ARRAYS:
a three-dimensional array (often referred to as a 3D array) extends the concept of a 2D
array into an additional dimension, allowing you to store data in a three-dimensional
grid. This can be thought of as a "cube" of data, where each element is accessed using
three indices: one for the depth (or layer), one for the row, and one for the column.
Declaring and Initializing a 3D Array
Declaration
To declare a 3D array in Java, you specify the type of the elements followed by three
sets of square brackets:
java
Copy code
int[][][] cube;
Initialization
You can initialize a 3D array either statically or dynamically.
1. Static Initialization
If you know the values at compile time, you can initialize the array with values
directly:
int[][][] cube = {
{
{1, 2, 3},
{4, 5, 6}
},
{
{7, 8, 9},
{10, 11, 12}
}
};
2. Dynamic Initialization
You can create a 3D array and then initialize it:

public class ThreeDArrayExample {


public static void main(String[] args) {
int[][][] cube = new int[2][2][3]; // 2 layers, 2 rows per layer, 3 columns per row

// Initialize elements
cube[0][0][0] = 1;
cube[0][0][1] = 2;
cube[0][0][2] = 3;
cube[0][1][0] = 4;
cube[0][1][1] = 5;
cube[0][1][2] = 6;
cube[1][0][0] = 7;
cube[1][0][1] = 8;
cube[1][0][2] = 9;
cube[1][1][0] = 10;
cube[1][1][1] = 11;
cube[1][1][2] = 12;

// Print the 3D array


for (int i = 0; i < cube.length; i++) { // Iterate over layers
System.out.println("Layer " + i + ":");
for (int j = 0; j < cube[i].length; j++) { // Iterate over rows
for (int k = 0; k < cube[i][j].length; k++) { // Iterate over columns
System.out.print(cube[i][j][k] + " ");
}
System.out.println();
}
System.out.println();
}
}
}
Accessing Elements
To access or modify elements in a 3D array, use three indices: one for the depth
(layer), one for the row, and one for the column.

int value = cube[1][0][2]; // Accesses the element in the second layer, first row, third
column
Iterating Over a 3D Array
To traverse a 3D array, you use nested loops. The outermost loop iterates over layers,
the middle loop iterates over rows, and the innermost loop iterates over columns.
Example:

public class ThreeDArrayTraversal {


public static void main(String[] args) {
int[][][] cube = {
{
{1, 2, 3},
{4, 5, 6}
},
{
{7, 8, 9},
{10, 11, 12}
}
};

// Iterate over layers


for (int i = 0; i < cube.length; i++) {
System.out.println("Layer " + i + ":");
// Iterate over rows
for (int j = 0; j < cube[i].length; j++) {
// Iterate over columns
for (int k = 0; k < cube[i][j].length; k++) {
System.out.print(cube[i][j][k] + " ");
}
System.out.println();
}
System.out.println();
}
}
}

Common Operations
1. Finding the Size
You can find the size of each dimension using the length attribute:
int numLayers = cube.length; // Number of layers
int numRowsInLayer1 = cube[0].length; // Number of rows in the first layer
int numColsInRow1 = cube[0][0].length; // Number of columns in the first row of the
first layer
2. Copying a 3D Array
Copying a 3D array requires copying each layer, row, and column:

int[][][] copy = new int[cube.length][][];


for (int i = 0; i < cube.length; i++) {
copy[i] = new int[cube[i].length][];
for (int j = 0; j < cube[i].length; j++) {
copy[i][j] = cube[i][j].clone(); // Copies each row in the layer
}
}
3. Flattening a 3D Array
To get a 1D representation of a 3D array, you can flatten it:

int totalLength = 0;
for (int[][] layer : cube) {
for (int[] row : layer) {
totalLength += row.length;
}
}

int[] flat = new int[totalLength];


int index = 0;
for (int[][] layer : cube) {
for (int[] row : layer) {
for (int element : row) {
flat[index++] = element;
}
}
}
Summary
 Declaration: int[][][] cube;
 Initialization: Use either static values or dynamic allocation with specified
dimensions.
 Access: Use [layer][row][column] to get or set values.
 Iteration: Use three nested loops to traverse the array.
 Operations: Includes finding sizes, copying, and flattening.

VECTORS:
arrays and vectors are both used to store collections of elements, but they have some
key differences and use cases. Here's an explanation of how arrays and vectors are
used in Java, including their characteristics, differences, and when you might use one
over the other.
Arrays in Java
Arrays in Java are a fundamental data structure that allows you to store a fixed-size
sequence of elements of the same type. Arrays are a core part of the Java language and
offer efficient, indexed access to elements.
Characteristics:
 Fixed Size: Once an array is created, its size cannot be changed.
 Indexed Access: Elements are accessed using zero-based indices.
 Type-Specific: All elements in an array must be of the same type (e.g., int[],
String[]).
 Performance: Arrays offer constant-time access (O(1)) to elements.
Example:
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = new int[5]; // Create an array of 5 integers

// Initialize the array


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

// Access and print elements


for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
Vectors in Java
Vectors are part of the Java Collections Framework and are more versatile than
arrays. They are essentially resizable arrays, meaning their size can grow or shrink
dynamically.
Characteristics:
 Resizable: Vectors can grow or shrink in size as needed.
 Indexed Access: Like arrays, elements are accessed using zero-based indices.
 Thread-Safe: Vector is synchronized, making it thread-safe (but this also
makes it less efficient in single-threaded scenarios compared to non-
synchronized collections).
 Part of Legacy Collection Framework: Vector is a part of Java's original
collection framework but is now mostly replaced by ArrayList in the newer
collections framework.
Example:
import java.util.Vector;

public class VectorExample {


public static void main(String[] args) {
Vector<Integer> vector = new Vector<>(); // Create a Vector

// Add elements to the Vector


vector.add(10);
vector.add(20);
vector.add(30);
vector.add(40);
vector.add(50);

// Access and print elements


for (int i = 0; i < vector.size(); i++) {
System.out.println(vector.get(i));
}
}
}
Comparison: Arrays vs. Vectors

Feature Arrays Vectors

Size Fixed size Dynamic size (resizable)

Faster due to direct


Performance Slightly slower due to synchronization
memory access

Type-specific Type-safe with generics (for non-primitive


Type Safety
(homogeneous) types)
Feature Arrays Vectors

Thread
Not synchronized Synchronized, thread-safe
Safety

Basic operations (access, Rich API with methods like add(),


API
iteration) remove(), insertElementAt()

When to Use Arrays vs. Vectors


 Use Arrays:
o When you need a fixed-size, high-performance data structure.
o When the size of the collection is known and doesn't change.
o For scenarios where you need the simplest and most efficient access to
elements.
 Use Vectors:
o When you need a dynamically resizing array.
o When you require synchronization in multi-threaded environments
(although alternatives like ArrayList with manual synchronization are
often preferred for better performance).
o For legacy code or scenarios where thread safety is a concern.
Summary
 Arrays are simple and efficient for fixed-size collections with constant-time
access but lack flexibility.
 Vectors provide dynamic resizing and synchronization but come with overhead
due to synchronization and are part of the older collection framework.
For most modern applications, ArrayList (a part of the newer Java Collections
Framework) is preferred over Vector due to its performance benefits and more flexible
API.

You might also like