Forms of Array
•arrayis a collection of elements of the same data
type, stored in contiguous memory locations
3.
Types of Arraysin Java:
1. One-Dimensional Array
• A linear array with elements stored sequentially.
• Example:
• int[] numbers = {1, 2, 3, 4, 5}; // Declaration and
initialization
4.
Types of Arraysin Java:
2. Two-Dimensional Array
• A matrix-like structure where each element is accessed using
two indices
• Example:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
5.
Types of Arraysin Java:
3. Multi-Dimensional Array:
• Arrays with more than two dimensions.
• Example:
int[][][] cube = {
{
{1, 2},
{3, 4}
},
{
{5, 6},
{7, 8}
}
};
6.
Basic Operations onArray
1. Declaration and Initialization
• Declaration: Specify the type and size
• Example:
• int[] arr = new int[5]; // Array of size 5
• Initialization: Assign values to elements.
• Example:
• arr[0] = 10; // Assign value to the first element
7.
Basic Operations onArray
2. Traversing an Array
• Example:
public class Main {
public static void main(String[] args) {
int[] arr = {10, 20, 30, 40, 50};
for (int i = 0; i < arr.length; i++) {
System.out.println("Element at index " + i + ": " + arr[i]);
}
}
}
8.
Basic Operations onArray
3. Searching an Array
1. Linear Search: Search element sequentially
• Example:
int[] arr = {10, 20, 30, 40};
int key = 30;
for (int i = 0; i < arr.length; i++)
{
if (arr[i] == key) {
System.out.println("Found at index: " + i);
}
}
9.
Basic Operations onArray
3. Searching an Array
2. Linear Search: Search element sequentially
• Example:
Arrays.sort(arr);
int index = Arrays.binarySearch(arr, key);
System.out.println("Found at index: " + index);
10.
Basic Operations onArray
4. Updating an Element
• Example:
arr[2] = 100; // Update the third element
11.
Basic Operations onArray
5. Deleting an Element
• In Java, you cannot directly delete elements; instead, shift elements
or use collections like ArrayList
• Example:
for (int i = index; i < arr.length - 1; i++)
{
arr[i] = arr[i + 1];
}
12.
Memory Address Calculation
•How Arrays are Stored in Memory:
• Arrays in Java are objects stored in heap memory.
• The base address (starting memory location) and size of each element
determine the memory layout.
• Calculation of Memory Address:
• The memory address of an element can be calculated as:
• Address=Base Address+(Index × Size of Element)