What is Array?
An array in Java is a fixed-size collection of elements of the same data type. It allows you to store and access multiple values under a single variable name. Arrays are indexed starting from 0 and are useful for managing collections of data efficiently.
Why do we need Arrays?
Arrays are essential because they:
- Group related data under one variable.
- Allow efficient access to individual elements.
- Optimize memory usage.
- Facilitate iteration through elements.
- Enable passing data to functions efficiently.
Syntax of Array
In Java, the syntax for declaring and initializing an array is as follows:
// Example: declaring and initializing an array of integers with a size of 5
int[] numbers = new int[5];
Alternatively, you can declare and initialize the array in separate steps:
int[] numbers; // Declaration
numbers = new int[5]; // Initialization
You can also initialize the array with values:
// Example: initializing an array of integers with specific values
int[] numbers = {10, 20, 30, 40, 50};
How does Array work?
Arrays in Java store elements of the same data type in consecutive memory locations, accessible by index starting from 0. They have a fixed size and are efficient for accessing and manipulating data.
Internal working of an Array
Internally, arrays in Java are implemented as contiguous blocks of memory where elements of the same data type are stored sequentially. Here's a deeper look at how arrays work internally in Java:
Memory Allocation: When you declare an array in Java, memory is allocated for it based on the specified size and data type. This memory allocation is done from the heap, the region of memory reserved for dynamic memory allocation in Java.
Contiguous Storage: Array elements are stored consecutively in memory, one after another. This contiguous storage ensures efficient memory access, as elements can be accessed directly using their indices.
Indexing: Each element in the array is assigned an index starting from 0. When you access an element of the array using its index, the Java runtime calculates the memory address of the element based on its index and the size of the data type.
Element Access: Once the memory address of the desired element is calculated, the runtime retrieves the value stored at that address and returns it to the program. This process of accessing elements by index is very efficient, typically taking constant time, O(1).
Fixed Size: Arrays in Java have a fixed size, meaning their size cannot be changed after they are created. If you need to store more elements than the size of the array allows, you would need to create a new array with a larger size and copy the elements from the old array to the new one.
Primitive vs. Reference Types: Arrays can hold elements of primitive data types (such as int, float, char) or reference types (such as objects). When an array holds elements of reference types, it actually holds references (memory addresses) to the objects rather than the objects themselves.
Garbage Collection: Arrays, like other objects in Java, are subject to automatic garbage collection. Once an array is no longer referenced by any part of the program, it becomes eligible for garbage collection, and the memory it occupies is reclaimed by the JVM.
Overall, arrays provide a low-level mechanism for efficiently storing and accessing collections of elements in memory, making them a fundamental data structure in Java.
Continuity of an Array
Array objects are typically located in the heap. In Java, arrays are objects, and as such, they are allocated memory on the heap.
Heap objects are not necessarily stored contiguously. While the elements within an array object are contiguous, the overall structure of the heap doesn't guarantee that objects are stored consecutively.
Dynamic Memory Allocation is indeed used for arrays and other objects in Java. Memory for arrays is allocated at runtime, allowing for flexibility in memory usage.
Therefore, while the elements within an array are guaranteed to be stored contiguously, the arrangement of objects in the heap may not be continuous. This behavior is dependent on how the JVM manages memory.
Index of an Array
The index of an array is a numeric value representing the position of an element within the array. It starts from 0, increments by 1 for each subsequent element, and allows for direct access to array elements.
New Keyword
The new
keyword in Java is used to dynamically allocate memory for objects at runtime. It creates instances of classes, allocates memory on the heap, invokes constructors to initialize objects, returns references to the allocated memory, and enables automatic garbage collection.
String Array
A string array in Java is an array that holds elements of type String. It allows you to store multiple strings under a single variable name, making it useful for managing collections of text data.
What is null in JAVA?
null
in Java represents the absence of a value or an uninitialized object reference. It's used to indicate that a variable does not currently refer to any object and can lead to a NullPointerException
if accessed improperly.
Array Input
For loop
Scanner scanner = new Scanner(System.in);
// Get the size of the array from the user
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
// Create the array
int[] numbers = new int[size];
// Input the elements of the array
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
numbers[i] = scanner.nextInt();
}
// Display the elements of the array
System.out.println("The elements of the array are:");
for (int i = 0; i < size; i++) {
System.out.println(numbers[i]);
}
For each loop
Scanner scanner = new Scanner(System.in);
// Get the size of the array from the user
System.out.print("Enter the size of the array: ");
int size = scanner.nextInt();
// Create the array
int[] numbers = new int[size];
// Input the elements of the array
System.out.println("Enter the elements of the array:");
for (int i = 0; i < size; i++) {
numbers[i] = scanner.nextInt();
}
// Display the elements of the array using for-each loop
System.out.println("The elements of the array are:");
for (int number : numbers) {
System.out.println(number);
}
toString() Method
int[] numbers = {1, 2, 3, 4, 5};
String str = Arrays.toString(numbers);
System.out.println(str); // Output: [1, 2, 3, 4, 5]
Storage of objects in heap
Objects in Java are stored in the heap memory. When you create an object using the new
keyword, memory is allocated on the heap to store its data, and a reference to this memory location is returned. Java's automatic garbage collection manages memory deallocation, ensuring efficient use of heap memory resources.
Array passing in function
You can pass arrays as parameters to functions in Java, allowing you to work with array elements within the function. Modifications made to the array within the function affect the original array. This enables modularization and reusability of code when working with arrays.
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
printArray(numbers); // Pass the array to the function
}
// Function to print array elements
public static void printArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
Multi-dimensional Arrays
Syntax of 2D Array
Internal working of 2D Array
can be written like
int[][] arr = new int[3][];
individual arrays can have different size
2D Array input
2D Array output
Arrays are Mutable
Dynamic Arrays
What is ArrayList
What's your thoughts?
Please Register or Login to your account to be able to submit your comment.