Understanding Arrays
Array Definition
An array represents a collection of elements with identical data types, occupying contiguous memory locations.
- All stored elements maintain consistent type
- Memory allocation occurs in sequential blocks
- Each location has an assigned identifier starting from zero (index)
Array Creation and Initialization
Creating Arrays
Syntax: T[] variableName = new T[N];
Where:
- T: element type stored in the array
- T[]: array type declaration
- N: array size/length
public static void executeMain(String[] parameters) {
int[] container1 = new int[5]; // Creates space for 5 integer values
double[] container2 = new double[5]; // Creates space for 5 floating-point values
String[] container3 = new String[5]; // Creates space for 5 string objects
}
container1, container2, container3 are reference variables.
Initialization Methods
Two primary initialization approaches exist: dynamic and static.
Dynamic Initialization: Specify element count during creation.
int[] numbers = new int[10];
Static Initialization: Define specific data values without explicitly stating size.
Syntax: T[] variableName = {value1, value2, value3, ..., valueN};
public static void executeMain(String[] parameters) {
int[] sequence1 = new int[]{1, 2, 3, 4, 5};
double[] sequence2 = new double[]{1.5, 2.5, 3.5, 4.5, 5.5};
String[] sequence3 = new String[]{"forward", "ever", "onward"};
}
Important considerations:
- Compiler determines length based on {} contents in static initialization
- Data types within {} must match declared type before []
- Abbreviated syntax omits new T[] portion
public static void executeMain(String[] parameters) {
int[] sequence1 = {1, 2, 3, 4, 5};
double[] sequence2 = {1.5, 2.5, 3.5, 4.5, 5.5};
String[] sequence3 = {"forward", "ever", "onward"};
}
Uninitialized arrays contain default values:
| Type | Default Value |
|---|---|
| byte | 0 |
| short | 0 |
| int | 0 |
| long | 0L |
| float | 0.0f |
| double | 0.0 |
| char | \u0000 |
| boolean | false |
Array Element Access
Sequential memory allows direct access through indices starting at zero.
public static void executeMain(String[] parameters) {
int[] values = new int[]{1, 2, 3, 4, 5};
System.out.println(values[0]);
System.out.println(values[1]);
System.out.println(values[2]);
System.out.println(values[3]);
System.out.println(values[4]);
// Modify elements using bracket notation
values[0] = 100;
System.out.println(values[0]);
}
Index bounds: [0, N) where N equals element count. Exceeding bounds triggers ArrayIndexOutOfBoundsException.
Array Traversal Techniques
Complete iteration involves accessing all elements systematically.
Traditional loop with length property:
public static void executeMain(String[] parameters) {
int[] values = new int[]{1, 2, 3, 4, 5};
for (int position = 0; position < values.length; position++) {
System.out.print(values[position] + " ");
}
}
Enhacned for-loop (for-each):
public static void executeMain(String[] parameters) {
int[] values = new int[]{1, 2, 3, 4, 5};
for (int item : values) {
System.out.print(item + " ");
}
}
Using Arrays.toString() method:
import java.util.Arrays;
public static void executeMain(String[] parameters) {
int[] values = new int[]{1, 2, 3, 4, 5};
String result = Arrays.toString(values);
System.out.println(result); // Output: [1, 2, 3, 4, 5]
}
JVM Memory Distribution Overview
Memory Segments
- Program Counter Register: Stores address of next instruction
- Java Virtual Machine Stack: Method-related data including local variables, operand stack
- Native Method Stack: Handles native method calls
- Heap: Largest JVM-managed region where object instances reside
- Method Area: Stores class metadata, constants, static variables
Reference Variables
Primitive variables store actual values directly, while reference variables hold object addresses.
public static void executeMain(String[] parameters) {
int primitiveValue = 10;
System.out.println(primitiveValue);
int[] referenceArray = new int[]{1, 2, 3, 4, 5};
System.out.println(referenceArray); // Output: [I@hexadecimal_address
}
Null Reference Concept
null indicates absence of object reference. Attempting operations on null triggers NullPointerException.
Array Practice Examples
Converting Arrays to Strings
import java.util.Arrays;
public static void executeMain(String[] parameters) {
int[] numbers = new int[]{1, 2, 3, 4, 5};
System.out.println(Arrays.toString(numbers)); // Output: [1, 2, 3, 4, 5]
}
Calculating Average Values
public static void executeMain(String[] parameters) {
int[] numbers = new int[]{1, 2, 3, 4, 5};
int total = 0;
for (int position = 0; position < numbers.length; position++) {
total += numbers[position];
}
double average = (double) total / numbers.length;
System.out.println(average);
}
Linear Search Implementation
public static int locateElement(int[] dataset, int target) {
for (int position = 0; position < dataset.length; position++) {
if (dataset[position] == target) {
return position;
}
}
return -1;
}
public static void executeMain(String[] parameters) {
int[] numbers = new int[]{1, 12, 23, 34, 45};
int foundIndex = locateElement(numbers, 12);
System.out.println(foundIndex); // Output: 1
}
Binary Search Algorithm
Efficient for sorted sequences. Compares target with midddle element and narrows search range.
public static int locateElement(int[] sortedData, int target) {
int start = 0;
int end = sortedData.length - 1;
while (start <= end) {
int middle = start + (end - start) / 2;
if (sortedData[middle] == target) {
return middle;
} else if (sortedData[middle] < target) {
start = middle + 1;
} else {
end = middle - 1;
}
}
return -1;
}
public static void executeMain(String[] parameters) {
int[] sortedNumbers = new int[]{1, 12, 23, 34, 45};
int foundIndex = locateElement(sortedNumbers, 12);
System.out.println(foundIndex); // Output: 1
}
Built-in binary search:
import java.util.Arrays;
public static void executeMain(String[] parameters) {
int[] sortedNumbers = new int[]{1, 12, 23, 34, 45};
int foundIndex = Arrays.binarySearch(sortedNumbers, 12);
System.out.println(foundIndex); // Output: 1
}
Bubble Sort Implementation
Repeatedly compares adjacent elements and swaps if unordered.
import java.util.Arrays;
public static void performBubbleSort(int[] data) {
for (int pass = 0; pass < data.length - 1; pass++) {
boolean swapped = false;
for (int current = 0; current < data.length - 1 - pass; current++) {
if (data[current] > data[current + 1]) {
int temporary = data[current];
data[current] = data[current + 1];
data[current + 1] = temporary;
swapped = true;
}
}
if (!swapped) break;
}
}
public static void executeMain(String[] parameters) {
int[] unsorted = new int[]{2, 33, 5, 66, 7, 88, 9};
System.out.println("Original: " + Arrays.toString(unsorted));
performBubbleSort(unsorted);
System.out.println("Sorted: " + Arrays.toString(unsorted));
}
Built-in sorting:
import java.util.Arrays;
public static void executeMain(String[] parameters) {
int[] data = new int[]{2, 33, 5, 66, 7, 88, 9};
System.out.println("Before: " + Arrays.toString(data));
Arrays.sort(data);
System.out.println("After: " + Arrays.toString(data));
}
Array Reversal
import java.util.Arrays;
public static void reverseSequence(int[] data) {
int front = 0;
int rear = data.length - 1;
while (front < rear) {
int temp = data[front];
data[front] = data[rear];
data[rear] = temp;
front++;
rear--;
}
}
public static void executeMain(String[] parameters) {
int[] original = new int[]{1, 2, 3, 4, 5};
System.out.println("Initial: " + Arrays.toString(original));
reverseSequence(original);
System.out.println("Reversed: " + Arrays.toString(original));
}
Array Copying
import java.util.Arrays;
public static int[] duplicateArray(int[] source) {
int[] destination = new int[source.length];
for (int index = 0; index < source.length; index++) {
destination[index] = source[index];
}
return destination;
}
public static void executeMain(String[] parameters) {
int[] original = new int[]{1, 2, 3, 4, 5};
int[] duplicated = duplicateArray(original);
System.out.println(Arrays.toString(duplicated));
}
Built-in copying:
import java.util.Arrays;
public static void executeMain(String[] parameters) {
int[] original = new int[]{1, 2, 3, 4, 5};
int[] duplicated = Arrays.copyOf(original, original.length);
System.out.println(Arrays.toString(duplicated));
}
Two-Dimensional Arrays
Conceptual one-dimensional arrays where each element contains another array.
public static void executeMain(String[] parameters) {
int[][] matrix1 = {{1, 2, 3}, {4, 5, 6}};
int[][] matrix2 = new int[][]{{1, 2, 3}, {4, 5, 6}};
int[][] matrix3 = new int[2][3];
int[][] matrix4 = new int[2][];
}
Accessing and displaying 2D arrays:
public static void executeMain(String[] parameters) {
int[][] grid = {{1, 2, 3}, {4, 5, 6}};
System.out.println(grid.length); // Row count
System.out.println(grid[0].length); // Column count
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
System.out.print(grid[row][col] + " ");
}
System.out.println();
}
}