Arrays in Java
An array is a collection of elements of the same data type stored in contiguous memory locations. It allows multiple values to be stored under a single
name and accessed using an index.
Declaring an Array
In Java, an array is declared by specifying the data type, followed by the array name, and empty square brackets [].
dataType[] arrayName;
or
dataType arrayName[];
Initialization of an Array
When an array is declared, only a reference is created. Memory is allocated using the new keyword by specifying the array size.
int arr[] = new int[size];
Once an array is created, its size is fixed and cannot be changed. For collections that can grow or shrink dynamically, Java provides classes like ArrayList.
Initialization using Array Literal
You can use array literals to initialize an array when declaring it. In this case, the new keyword is not required-
Example:
int[] arr = {1, 2, 3};
The length of this array determines the length of the created array; There is no need to write the new int[] part.
Page 1 of 13
Arrays Class in Java
The Arrays class in [Link] is a utility class that provides static methods to perform operations like sorting, searching, comparing, and converting arrays. It
cannot be instantiated and is used only for utility purposes.
Provides static methods such as sort(), binarySearch(), equals(), toString().
Operations on Array Elements
1. Access Array Elements
Elements of an array can be accessed by their position, called the index. In Java, array indexing starts from 0 (not 1). To access an element, provide the index
inside square brackets [] along with the array name.
Note: It is important to note that index cannot be negative or greater than size of the array minus 1. (0 ≤ index ≤ size - 1). Also, it can also be any expression
that results in valid index value.
2. Update Array Elements
To update an element at a specific index in an array, use the assignment operator = while accessing the array element and assign a new value.
Page 2 of 13
3. Traverse Array
Traversing an array means accessing each element one by one. In Java, arrays can be easily traversed using a loop where the loop variable runs from 0 to
[Link] - 1.
4. Size of Array
The size of an array refers to the number of elements it can hold. To find the size of array java provides a built-in property called length.
Page 3 of 13
Arrays of Objects in Java
An array of objects is created like an array of primitive-type data items
Example: Create an array of five Student objects by instantiating each Student using its constructor and storing their references in the array.
Page 4 of 13
What happens if we try to access elements outside the array size?
JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been accessed with an illegal index. The index is either negative or greater than
or equal to the size of an array.
Output:
Passing Arrays to Methods
Like variables, we can also pass arrays to methods. For example, the below program passes the array to method sum to calculate the sum of the array's
values.
Page 5 of 13
Explanation
This Java program demonstrates how to pass an array to a method.
An integer array arr is declared and initialized in the main method.
The sum() method is called with arr as an argument.
Inside the sum() method, all array elements are added using a for loop.
The final sum is then printed.
Clarification about pass by value and pass by reference in java
In the above code, when you call:
sum(arr); // In Java, this is pass by value, which is the value of the reference (the memory address of the array), not the array itself.
Java is always pass by value, but for arrays (and objects), the value being passed is the reference.
What that means:
The method gets a copy of the reference
Both the original and the method point to the same array in memory
Page 6 of 13
So:
If you modify elements inside the array, it will affect the original array
If you reassign the array inside the method, it will NOT affect the original
Output:
Page 7 of 13
Returning Arrays from Methods
As usual, a method can also return an array. For example, the below program returns an array from method m1.
For-Each Loop in Java
The for-each loop in Java provides a simple, readable way to iterate over arrays and collections without using indexes.
Syntax
for (datatype variable : arrayOrCollection) {
// statements using variable
}
Parameters:
datatype: The data type of the elements in the array or collection.
variable: The variable that holds the current element during each iteration.
array: The array or collection being iterated over.
Example: Iterating Over an Array
Page 8 of 13
When to Use For-Each Loop?
Use for-each loop when:
We do not need the index of elements
We only need to read or process elements
Code readability and simplicity are important
When to Avoid For-Each Loop?
Avoid using for-each loop when:
Index-based access is required
Reverse iteration is needed
You need to modify elements of an array
Complex conditions depend on index positions
What are the limitations of the For-each Loop
1. Cannot Modify Primitive Array Elements
for (int num : marks) {
num = num * 2; // Does not modify array
}
Explanation:The loop variable holds a copy of the value, not the actual array element.
2. No Access to Index
3. Single-direction Iteration Only: The for-each loop allows only forward iteration. Reverse iteration requires a traditional for loop with an index.
Note:
The for-each loop works with arrays and all classes that implement Iterable
Internally, it uses an iterator for collections
Best suited for simple traversal and read-only operations
Example : Finding Maximum in an Array using for-each Loop
Page 9 of 13
Explanation:
The first element is assumed to be the maximum initially.
Each element is compared with the current maximum.
If a larger value is found, it replaces the previous maximum.
ArrayList in Java
ArrayList in Java is a resizable array provided in the [Link] package. Unlike normal arrays, its size can grow or shrink dynamically as elements are added
or removed.
Elements can be accessed using their indices, similar to arrays.
Elements are stored in the order they are inserted.
ArrayList is not thread-safe.
Page 10 of 13
Example 1:
Explanation: This program creates an ArrayList of integers, adds
elements to it using the add() method, and stores them dynamically.
Finally, it prints the elements in insertion order as [1, 2, 3].
Note:
ArrayList stores objects
Primitive values → use wrapper classes (Integer, Double, etc.)
ArrayList only stores objects, not primitive types like int, double, or char directly. In fact, an ArrayList only stores objects. We must use their wrapper classes
instead:
Use Integer instead of int
Use Double instead of double
Use Character instead of char
Page 11 of 13
Example 2: ArrayList is storing Student objects
ArrayList Methods
Operations of ArrayList
Page 12 of 13
1. OOP OOP OOP
2. OOP JAVA OOP OOP
3. JAVA OOP OOP
4. JAVA OOP
5. OOP OOP
Page 13 of 13