0% found this document useful (0 votes)
2 views19 pages

Copy of Session 13 - Arrays Part 1 - Introduction to Arrays

This document provides an overview of arrays in Java, detailing their characteristics, types, and memory storage. It explains one-dimensional, two-dimensional, and multi-dimensional arrays, along with their declaration, initialization, and access methods. Additionally, it covers memory allocation, efficiency, and default values assigned to array elements in Java.

Uploaded by

pavankumarvoore3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views19 pages

Copy of Session 13 - Arrays Part 1 - Introduction to Arrays

This document provides an overview of arrays in Java, detailing their characteristics, types, and memory storage. It explains one-dimensional, two-dimensional, and multi-dimensional arrays, along with their declaration, initialization, and access methods. Additionally, it covers memory allocation, efficiency, and default values assigned to array elements in Java.

Uploaded by

pavankumarvoore3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

OBJECT-ORIENTED PROGRAMMING

THROUGH JAVA

UNIT - III

Session 13 - Arrays - Part 1

1. Introduction to Arrays

Introduction to Arrays in Java


Arrays in Java are a fundamental data structure that allow you to store multiple values of the
same type in a single variable. They are particularly useful when you need to manage
collections of data, such as a list of numbers, names, or objects, without having to declare
separate variables for each individual element.

Key Characteristics of Arrays:


1. Fixed Size: Once an array is created, its size is fixed and cannot be changed. This
means you must know the number of elements you need in advance.
2. Homogeneous Elements: All elements in an array must be of the same data type (e.g.,
int[] for integers, String[] for strings).
3. Zero-based Indexing: In Java, array indexing starts at 0. The first element of an array is
accessed via index 0, the second element via index 1, and so on.
4. Direct Memory Access: Arrays provide fast access to elements since each element can
be directly accessed using its index.

Why Use Arrays?


- Efficient Data Storage: Arrays allow storing multiple values using a single variable,
making your code more organized.
- Efficient Access: Indexes make it easy to access, update, or manipulate any element
within an array.
- Memory Management: Arrays are stored in contiguous memory locations, making them
efficient in terms of memory usage.

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:

int[] marks = new int[10]; // Array to store marks of 10 students



In this case, you have declared an array that can store marks for 10 students. Each student's
marks can be accessed or updated using their index in the array.

Types of Arrays in Java


There are three main types of arrays in Java, which are used according to the program’s
requirements. These are:
1. One-dimensional Array (1D Array)
A one-dimensional array, also known as a linear array, stores elements in a single row. It is a
simple list of elements stored in adjacent memory locations, where each element can be
accessed using a single index.

Example: int[] array = {1, 2, 3, 4, 5};

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:

for (int i = 0; i < array.length; i++) {


System.out.println(array[i]);
}

This loop will print:
1
2
3
4
5

2. Two-dimensional Array (2D Array)


A two-dimensional array stores data in rows and columns, similar to a table or matrix. Each
element is accessed using two indices: one for the row and one for the column.

Example: int[][] array = { {1, 2, 3}, {4, 5, 6} };

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:

for (int i = 0; i < array.length; i++) {


for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println(); // Move to the next line after each row
}

The output will be:

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.

2. Single (One-Dimensional) Arrays


Declaration and Initialization of Arrays in Java

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:

int[] num; // Declares an array of integers


String[] names; // Declares an array of strings

At this point, the array is declared but has no memory allocated for its elements.

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:

a. Using new Keyword


You can initialize an array by specifying the size (number of elements) using the new keyword.
This allocates memory for the specified number of elements.

Syntax:

arrayName = new dataType[size];



Example:
num = new int[10]; // Allocates memory for 10 integers

Now, memory is allocated for 5 integers, and each element in the array is automatically
initialized to the default value (0 for integers).

You can combine declaration and initialization in one line:

int[] numbers = new int[5]; // Declares and allocates memory for an array of 5
integers

b. Initializing with Values Directly


You can also initialize the array with specific values at the time of declaration without specifying
the size, as the size is inferred from the number of values provided.

Syntax:

dataType[] arrayName = {value1, value2, value3, ...};



Example:

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:

numbers[0] = 100; // Changes the first element to 100


int first = numbers[0]; // Retrieves the first element

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

1. What is the correct way to declare a one-dimensional array of integers in Java?

a) int array[10];
b) int[] array = new int(10);
c) int[] array = new int[10];
d) int array[] = 10;

Answer: c) int[] array = new int[10];

2. Consider the following code:

int[] numbers = {10, 20, 30, 40, 50};


System.out.println(numbers[2]);

What will be the output of the program?

a) 10
b) 20
c) 30
d) ArrayIndexOutOfBoundsException

Answer: c) 30

3. Identify the bug in the following code:

int[] arr = new int[5];


arr[5] = 25;
System.out.println(arr[5]);

a) The array is not initialized.
b) The index 5 is out of bounds.
c) The size of the array is wrong.
d) The code is correct.

Answer: b) The index 5 is out of bounds.

4. Complete the following code to initialize the array correctly:

int[] ages = ___ {21, 25, 30, 35, 40};



a) new
b) new int
c) new[]
d) None of the above

Answer: b) new int

5. What is the default value of elements in an uninitialized int array in Java?

a) 1
b) -1
c) 0
d) null

Answer: c) 0

6. What will be the output of the following code?

int[] numbers = new int[3];


numbers[0] = 10;
System.out.println(numbers[1]);

a) 0
b) 10
c) null
d) ArrayIndexOutOfBoundsException

Answer: a) 0
3. Storage of Array in Computer Memory

Storage of Array in Computer Memory


Arrays are one of the fundamental data structures used to store collections of elements. In Java,
arrays are stored in a specific way in memory to ensure efficiency and fast access. Let's explore
how arrays are stored in memory, focusing on the following aspects:

1. Contiguous Memory Allocation


When an array is created in Java, the elements are stored in contiguous memory locations.
This means that the array elements are placed one after the other in a continuous block of
memory. The size of the block allocated depends on two factors:

● The number of elements in the array.


● The size of each element, which is determined by the data type (e.g., int, char,
double).

For instance, if you declare an array of 5 integers:

int[] arr = new int[5];



Each int element in Java takes up 4 bytes of memory. Therefore, this array will occupy 5 * 4
= 20 bytes of memory in a contiguous block.

Visualization of memory layout for an array like:

int[] arr = {1, 2, 3, 4, 5};



would look like this:
Each element is placed sequentially, with the next element's address being calculated by
adding the size of one element (in this case, 4 bytes) to the previous address.

2. Heap and Stack Memory Allocation


Java uses heap memory to store objects, and since arrays are considered objects in Java, the
array elements are stored in the heap. However, the reference (or pointer) to the array is stored
in stack memory, which holds local variables and method call references.

● Stack Memory: Contains the reference (or pointer) to the array object.
● Heap Memory: Contains the actual array elements.

For example:

int[] numbers = new int[5];



● The reference to numbers is stored in stack memory.
● The array elements (5 integers in this case) are stored in heap memory.

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:

Memory Address of element i = Base Address + (i * Size of each element)



Here:
● Base Address is the memory address of the first element.
● i is the index of the element.
● Size of each element is the size (in bytes) of the data type.

For example, in an integer array:

int[] numbers = {5, 10, 15, 20};



● The memory address of numbers[2] would be calculated as:
Base Address + (2 * 4), since each int is 4 bytes.

4. Memory Efficiency and Access Speed


Due to the contiguous layout of arrays in memory, accessing elements is extremely efficient.
The time complexity of accessing an array element by index is O(1), meaning it takes constant
time. This is one of the key reasons why arrays are favored for scenarios requiring fast, direct
access to elements.

The contiguous memory layout offers:

● 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.

5. Default Values in Arrays


When an array is created but not explicitly initialized, Java assigns default values to each
element. These default values depend on the data type of the array:

● int, byte, short, long: 0


● float, double: 0.0
● char: **'\u0000'` (null character)
● boolean: false
● Object references: null

For example:

int[] arr = new int[3];



The above code will create an array of 3 integers, all initialized to 0 by default.
6. Memory Limitation and Array Size
Although arrays are memory-efficient, they come with certain limitations:

● 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.

int[] myArray = new int[5];

for (int i = 0; i <= 5; i++) {

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.

4. Accessing Elements of Arrays

Accessing Elements of Arrays

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.

Syntax for Accessing Array Elements


To access an element from an array, you use the following syntax:

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};

// Access elements from the array


System.out.println("First element: " + numbers[0]); // Output: 10
System.out.println("Second element: " + numbers[1]); // Output: 20
System.out.println("Third element: " + numbers[2]); // Output: 30

// Change the value of an element


numbers[3] = 100;
System.out.println("Updated fourth element: " + numbers[3]); // Output: 100
}
}

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;

public class ArrayExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Ask user for the number of elements in the array


System.out.print("Enter the number of elements: ");
int n = scanner.nextInt();

// Declare an array of size n


int[] arr = new int[n];

// Take input from the user


System.out.println("Enter " + n + " elements:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

// Display the elements of the array


System.out.println("Array elements are:");
for (int i = 0; i < n; i++) {
System.out.println("Element at index " + i + " is: " + arr[i]);
}

// Calculate and display the sum of the elements


int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
System.out.println("Sum of array elements: " + sum);
}
}

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.

3. Create a program to declare an array of 7 floating-point numbers, calculate their sum,


and print both the array and the sum.

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.

3. What is the index of the last element in an array of size 10?


a) 10
b) 9
c) 8
d) 11
Answer: b) 9

4. Which of the following is the correct declaration of an array in Java?


a) int arr[] = new int(5);
b) int arr[] = new int[5];
c) int arr() = new int[5];
d) int[] arr = new int(5);
Answer: b) int arr[] = new int[5];

5. How are array elements stored in memory in Java?


a) Random locations
b) Contiguously in memory
c) In reverse order
d) Depends on the operating system
Answer: b) Contiguously in memory

References
End of Session - 6

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy