Copy of Session 13 - Arrays Part 1 - Introduction to Arrays
Copy of Session 13 - Arrays Part 1 - Introduction to Arrays
THROUGH JAVA
UNIT - III
1. Introduction to Arrays
If you need to store 50 integer values, you can create an array that can hold all 50 integers at
once. Instead of declaring separate variables like a1, a2, …, a49, you can declare a single
array that contains all 50 values. The values in the array can then be accessed using indices
such as a[0], a[1], …, a[49].
For example, if you need to store marks of 10 students, we don’t need to declare 10 variables.
Instead you can declare an array that can hold int-type values.
Programming Example:
Suppose you are developing an attendance tracking system. Instead of declaring individual
variables for each student’s attendance, you can use an array to store attendance data for all
students.
For example:
In this example, the array contains five elements: 1, 2, 3, 4, 5. The elements are stored in
a single row and can be accessed using indices like array[0] for the first element, array[1]
for the second, and so on.
Visualization:
[1, 2, 3, 4, 5]
In Java, you can use a for loop to iterate through the array and print each element. For
example:
This array has two rows and three columns. You can access each element using two indices,
like array[0][0] for the element in the first row and first column (1), or array[1][2] for the
element in the second row and third column (6).
Visualization:
[1, 2, 3]
[4, 5, 6]
To print all the elements of a 2D array, you can use nested for loops:
1 2 3
4 5 6
3. Multi-dimensional Array
A multi-dimensional array has more than two dimensions, such as 3D or 4D arrays. It can
store data in multiple layers, accessing each element using multiple indices.
Example: int[][][] array = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}};
This is a 3D array with two layers, each containing two rows and two columns. You can access
elements using three indices, like array[0][0][1] for the second element in the first row of
the first layer (2), or array[1][1][0] for the first element in the second row of the second
layer (7).
Visualization:
Layer 1:
[1, 2]
[3, 4]
Layer 2:
[5, 6]
[7, 8]
Despite having multiple dimensions, you can still use nested loops to access elements, but the
number of loops typically remains two for rows and columns, regardless of the array's
dimensionality.
Summary
● One-dimensional arrays store elements in a single row (linear structure).
● Two-dimensional arrays store elements in rows and columns (table or matrix-like
structure).
● Multi-dimensional arrays store elements in more than two dimensions (e.g., 3D
structures with layers).
These arrays are used depending on the complexity and structure of the data you need to store
and manipulate.
1. Declaration of Arrays
In Java, an array must first be declared before it can be used. The declaration defines the data
type of the elements that the array will hold and the array's name. However, declaring an array
does not allocate memory for its elements; it simply creates a reference to the array.
Syntax:
dataType[] arrayName;
OR
dataType arrayName[];
Both syntaxes are valid, but the first is more commonly used.
Example
Example:
2. Initialization of Arrays
After declaring an array, you need to allocate memory and assign values to its elements. There
are two common ways to initialize an array in Java:
Syntax:
int[] numbers = new int[5]; // Declares and allocates memory for an array of 5
integers
Syntax:
int[] numbers = {10, 20, 30, 40, 50}; // Initializes an array with 5 elements
This creates an array of size 5 and assigns the values 10, 20, 30, 40, and 50 to the respective
elements.
3. Accessing Array Elements
Once initialized, you can access or modify the elements of an array using their index.
Remember, array indices in Java start from 0.
Example:
Summary:
- Declaration: Defines the array’s data type and name.
- This creates an array of size 5 and assigns the values 10, 20, 30, 40, and 50 to the
respective elements.
- Initialization: Allocates memory and assigns values to the array.
- You can initialize an array using the new keyword or directly with a set of values.
Do It Yourself
1. Write a Java program to declare an array of char with the size of 5. Initialize the
array with the characters 'a', 'e', 'i', 'o', 'u'. Then, print out each element
in reverse order using a loop.
2. Write a Java program to declare an array of float with a size of 10. Initialize the
array with values from 1.1 to 10.1 (inclusive)
3. Declare and initialize a string array named fruits with the values "Apple",
"Banana", "Mango", "Orange".
4. What is the difference between declaring an array as int[] arr; and int
arr[]; in Java? Which one is preferred and why?
Quiz
a) int array[10];
b) int[] array = new int(10);
c) int[] array = new int[10];
d) int array[] = 10;
a) 10
b) 20
c) 30
d) ArrayIndexOutOfBoundsException
Answer: c) 30
a) 1
b) -1
c) 0
d) null
Answer: c) 0
Answer: a) 0
3. Storage of Array in Computer Memory
● Stack Memory: Contains the reference (or pointer) to the array object.
● Heap Memory: Contains the actual array elements.
For example:
3. Index-based Access
In Java, arrays are zero-indexed, meaning the first element is at index 0. The contiguous
memory allocation makes it possible to access any element directly using its index. The address
of any element in the array can be calculated using the following formula:
● Fast Access: You can quickly access any element in the array using its index.
● Memory Efficiency: Elements are stored compactly, without any extra overhead
between them.
For example:
● Fixed Size: Once an array is created, its size is fixed and cannot be changed. This
means you must know the size of the array in advance.
● Contiguous Memory Requirement: Since arrays require a contiguous block of
memory, large arrays may cause memory allocation issues if the system cannot find a
large enough block of free memory.
7. Garbage Collection
Java has an automatic Garbage Collector (GC) that deallocates unused memory. When an
array is no longer referenced, the garbage collector will eventually free the memory occupied by
the array in the heap. This helps avoid memory leaks, though it's important to ensure that arrays
that are no longer needed are dereferenced properly.
Arrays in Java are stored in contiguous memory blocks, with the actual elements stored in the
heap and the reference in the stack. This allows for efficient access to elements through
indexing, which is both time-efficient and memory-efficient. While arrays are highly optimized for
fixed-size collections, they are constrained by their fixed size and the need for contiguous
memory blocks. Understanding how arrays are stored helps developers make better decisions
when dealing with large collections of data in Java.
Do It Yourself
1. Write a Java program that declares and initializes an array of 10 integers. Print the
memory address (hashcode) of the array and discuss how Java manages memory for
the array and its elements.
2. Analyze the following code and find the bug related to memory usage or array storage.
Explain the issue and how to fix it.
myArray[i] = i * 10;
3. Given that Java arrays start indexing from 0, explain why attempting to access an
element outside the declared size (for example, array[5] in a 5-element array) causes
an ArrayIndexOutOfBoundsException. Provide a code snippet demonstrating this
behavior and explain how memory is affected by improper indexing.
4. Create two arrays in Java, one storing int values and another storing double values.
Write a program to display the size of each array in memory. Explain why the memory
required for each array differs even if both arrays have the same number of elements.
Introduction
In Java, arrays are a collection of elements of the same data type stored in contiguous memory
locations. Once an array is declared and initialized, each element can be accessed individually
using an index. The index starts at 0, meaning the first element is accessed using index 0, the
second element with index 1, and so on.
arrayName[index];
● arrayName: Name of the array.
● index: The position of the element you want to access (starting from 0).
Example
public class AccessArrayElements {
public static void main(String[] args) {
// Declare and initialize an array
int[] numbers = {10, 20, 30, 40, 50};
Explanation:
● The array numbers is declared with 5 integer elements.
● The elements are accessed using their index values: numbers[0], numbers[1], etc.
● The value of the fourth element is changed using numbers[3] = 100;.
Important Points:
● The index of the array starts from 0. So, numbers[0] refers to the first element.
● Trying to access an index that is out of bounds (greater than or equal to the array length)
will result in an ArrayIndexOutOfBoundsException.
Practice Program
Here’s a program that accepts input for an array, prints all the elements, and calculates the sum
of the elements.
import java.util.Scanner;
Explanation:
● This program demonstrates how to access and display array elements.
● It also calculates the sum of all elements in the array using a for loop.
Summary
● Accessing Array Elements: You can access array elements using their index, which
starts from 0.
● Array Index Out of Bounds: Trying to access an index greater than or equal to the
array size results in an ArrayIndexOutOfBoundsException.
● Array Access in Loops: Arrays are often accessed using loops to perform operations
like summing elements or printing values.
Do It Yourself
1. Write a Java program to declare an array of 5 integers. Ask the user to input 5 values,
store them in the array, and print all elements.
2. Write a program that initializes an array with 10 elements. Swap the values of the first
and last elements, then print the updated array.
4. Declare an array of 6 integers, and then replace the value at index 2 with the value at
index 4. Print the modified array.
5. Write a program that tries to access an element at an index greater than the array size.
Observe and explain the error you get.
Quiz
1. What is the correct way to access the 3rd element of an array named arr?
a) arr(2)
b) arr[3]
c) arr[2]
d) arr[1]
Answer: c) arr[2]
2. What happens if you try to access an array element with an index larger than the
array size?
a) The first element will be returned.
b) The program will crash without any message.
c) An ArrayIndexOutOfBoundsException is thrown.
d) The last element of the array will be returned.
Answer: c) An ArrayIndexOutOfBoundsException is thrown.
References
End of Session - 6