Arrays
π What is an Array?β
An array is a collection of elements of the same data type, stored in contiguous memory locations.
In simple Array in Java is a data structure that allows you to store multiple values of the same data type in a single variable, instead of declaring separate variables for each value.
Example:β
Instead of:
int mark1 = 90;
int mark2 = 85;
int mark3 = 76;
You can write:
int[] marks = {90, 85, 76};
β Key Pointsβ
- Arrays in Java are objects.
- Arrays can be of primitive types or objects.
- The size is fixed once declared.
π’ Array Declaration & Initializationβ
Syntax:β
datatype[] arrayName; // Preferred
datatype arrayName[]; // Legal but not preferred
Initialization:β
int[] numbers = new int[5]; // Declares array of size 5 with default values (0)
Declaration + Initialization:β
int[] marks = {90, 85, 76, 92, 88}; // Static initialization
ποΈ Memory Representationβ
Arrays are stored in contiguous memory locations, which allows efficient indexed access.
Index: 0 1 2 3 4
Data : 90 85 76 92 88
π Array Object in Javaβ
When you create an array, Java internally does:
int[] arr = new int[5];
Java creates an object of type int[] with default values set to 0.
π§ Default Valuesβ
| Data Type | Default Value |
|---|---|
| int | 0 |
| double | 0.0 |
| boolean | false |
| Object | null |
π Characteristics of Arrays in Javaβ
- Fixed Size: Once created, its size cannot be changed.
- Homogeneous Elements: All elements must be of the same type.
- Indexed Access: First index is 0, last index is (length - 1).
- Stored in Heap Memory: Arrays are objects in Java and allocated in heap.
π― Why Use Arrays?β
- Efficient Data Management: Store multiple elements without multiple variables.
- Indexed Access: Quickly access any element using its index.
- Improves Code Readability and Maintenance
π Accessing & Modifying Elementsβ
int[] arr = {10, 20, 30};
System.out.println(arr[1]); // Output: 20
arr[1] = 25;
π Looping through Arraysβ
For loop:β
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
Enhanced For loop (for-each):β
for (int num : arr) {
System.out.println(num);
}
π Array Lengthβ
int len = arr.length; // No parenthesis (it's a field, not method)
π§Ύ Types of Arraysβ
1. Single Dimensional Arrayβ
A simple linear structure:
int[] arr = {1, 2, 3};
2. Multi-Dimensional Arrayβ
Used to represent tables, matrices:
int[][] matrix = new int[3][3];
matrix[0][1] = 5;
Initialization Example:β
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
π§© Jagged Arraysβ
An array of arrays where inner arrays can have different lengths.
int[][] jagged = new int[2][];
jagged[0] = new int[3]; // Row 0 has 3 columns
jagged[1] = new int[2]; // Row 1 has 2 columns
βοΈ Common Operationsβ
Finding Maximum Element:β
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] > max)
max = arr[i];
}
Sum of Array:β
int sum = 0;
for (int n : arr)
sum += n;
π§° Utility Methods from java.util.Arraysβ
import java.util.Arrays;
Sorting:β
Arrays.sort(arr);
Printing:β
System.out.println(Arrays.toString(arr));
Comparing Arrays:β
boolean isEqual = Arrays.equals(arr1, arr2);
Copying Arrays:β
int[] copy = Arrays.copyOf(original, newLength);
β ArrayIndexOutOfBoundsExceptionβ
Occurs when accessing an index outside the range 0 to array.length - 1.
int[] arr = new int[3];
System.out.println(arr[5]); // Throws exception
π Pros & Consβ
β Advantages:β
- Fast access via index
- Simple to use
- Efficient in memory for fixed-size data
β Limitations:β
- Arrays are Fixed in size , once created it can;t be modified.
- No built-in dynamic resizing
- Arrays expect contiguos memory location in the memory for creation. It can;t make ise of disperse memory location.
- Can store only homogeneous type of data , canβt mix of data types
π Array vs ArrayList (Quick Comparison)β
| Feature | Array | ArrayList |
|---|---|---|
| Size | Fixed | Dynamic |
| Type Support | Primitives/Objects | Objects only |
| Performance | Faster (less overhead) | Slower (more overhead) |
| Utilities | Basic | Rich (add/remove/search) |
| Syntax | Native | Uses methods |
| Methods | Few | Rich API Support |
π Best Practicesβ
- Use enhanced for-loop when no index is needed.
- Validate index access to avoid exceptions.
- Prefer
ArrayListif dynamic resizing is needed.
π§ͺ Sample Programβ
import java.util.Arrays;
public class ArrayExample {
public static void main(String[] args) {
int[] nums = {5, 3, 7, 1};
Arrays.sort(nums);
for (int n : nums) {
System.out.println(n);
}
System.out.println("Max: " + nums[nums.length - 1]);
}
}
π§ͺ Internal Workingβ
- Java arrays are internally represented as zero-based indexed objects.
- The length is stored as
arr.length. - Java runtime checks every access for bounds (
ArrayIndexOutOfBoundsException).
π‘ When to Use Arraysβ
- When you know the number of elements in advance.
- When memory optimization is crucial.
- When you need fast access via index.
If you need dynamic size, prefer ArrayList.
β Summaryβ
- Arrays are essential building blocks for storing multiple items.
- Java treats arrays as objects.
- They offer fast access but have size limitations.
- Understanding arrays builds foundation for mastering collections, data structures, and algorithms.