Arrays
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.
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;
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
// Adding elements
list.add(1);
list.add(2);
list.add(3);
// Modifying elements
list.set(1, 20);
// Removing an element
list.remove(0);
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;
import java.util.Arrays;
if (index != -1) {
System.out.println("Found target at index: " + index);
} else {
System.out.println("Target not found.");
}
}
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.
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;
class Person {
String name;
int age;
@Override
public String toString() {
return name + " (" + age + ")";
}
}
// 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;
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:
// 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:
int[][] jaggedArray;
Initialization
You can initialize a jagged array by first creating the outer array and then initializing
each inner array separately.
// 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;
int value = jaggedArray[1][2]; // Accesses the element in the second row, third column
int totalLength = 0;
for (int[] row : jaggedArray) {
totalLength += row.length;
}
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:
// 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;
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:
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 totalLength = 0;
for (int[][] layer : cube) {
for (int[] row : layer) {
totalLength += row.length;
}
}
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
Thread
Not synchronized Synchronized, thread-safe
Safety