sample SLM (1)
sample SLM (1)
sample SLM (1)
Table of Contents
1.1. Introduction
1.2. Type of Arrays
1.2.1 One-dimensional Array
1.2.2 Multi-dimensional Array
1.3. Application of Array
1.4. Advantages
1.5. Disadvantages
1.6. Summary
1.7. Case Study
1.8. Terminal Questions
1.9. Answer
1.10. References
2
Learning Objectives
Declaring and initializing arrays: Learn how to declare an array, specify its size,
and initialize it with values.
3
1.1 Introduction
• Array in Java is index-based, the first element of the array is stored at the 0th
index, and 2nd element is stored on the 1st index, and so on.
• At the time of array creation, it is necessary to specify the size of the array
otherwise we will get compile time error.
• If we take array size with a negative value then we will get a run time exception
that is a negative value exception.
• If we are trying to access an array element with out of range index we will get an
exception that is an array index out-of-bound exception.
• Length is a final variable that is applicable only to the array. Length represents
the size of the array.
Creating an Array:
4
1.2 Types of Arrays
You create a single-dimensional array using the new operator specifying the array
element type and the number of elements. The following example declares an array
of five integers.
Syntax:
Graphical Presentation:
A[0] = 5;
A[1] = 6;
A[2] = 7;
A[3] = 8;
A[4] = 9;
Index 0 1 2 3 4
Value 5 6 7 8 9
5
Example:
import java.util.Scanner;
public class One_D_Array
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
Input:
Output:
45678
6
1.2.2 Multidimensional Array
Java, a multidimensional array is a data structure that allows you to store elements
in multiple dimensions, forming a matrix-like structure. It is essentially an array of
arrays, where each element of the outer array can itself be an array. This allows for
the creation of arrays with more than one dimension, such as two-dimensional
arrays (matrices), three-dimensional arrays.
Syntax:
Graphical Presentation:
1. In a two-dimensional array, the first index represents the ________ and the second index
represents the ________.
2. To assign initial values to the elements of a multidimensional array, you can use nested
________ statements.
3. To assign initial values to the elements of a multidimensional array, you can use nested
________ statements.
4. The row and column index always start from ________.
5. complete the loop to print 1, 2, 3 4, 5 (code = for(int I =____; i<_____;i++))
7
Example:
import java.util.Scanner;
public class One_D_Array
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
for(int i=0;i<Row_size;i++)
{
for(int j=0;j<Col_size;j++)
{
A[i][j]=sc.nextInt();
}
}
for(int i=0;i<Row_size;i++)
{
for(int j=0;j<Col_size;j++)
{
System.out.print(A[i][j]+" ");
}
System.out.println();
}
}
}
Input:
Enter the Row & Column size of 2D array.
33
Enter the array values.
555
666
777
Output:
555
666
777
8
1.3 Applications of array
Enabling image processing: Arrays are commonly employed for storing pixel
values in image processing applications. For instance, a two-dimensional array
can be employed to store the RGB values of an image.
9
1.4 Advantages
1. Efficient memory usage: Arrays in Java offer efficient memory utilization since
they store elements of the same type in a contiguous block of memory, without
requiring additional memory for pointers or node structures.
2. Direct element access: Arrays allow for direct random access to elements
based on their index, enabling fast retrieval and modification of specific elements
without the need to traverse the entire data structure.
3. Efficient iteration: Arrays support efficient iteration over elements using simple
for loops, allowing for quick processing of each element in the array
4. Cache locality: Due to their contiguous memory layout, arrays benefit from
cache locality, which improves data access speed by leveraging hardware
caching mechanisms.
10
1.5 Disadvantages
1. Fixed size: Arrays in Java have a fixed size and cannot be dynamically resized,
requiring manual management or the creation of new arrays when the size needs
to change.
4. Limited data type flexibility: Arrays in Java can only store elements of the
same type, making them less flexible for scenarios that require storing different
data types within a single data structure.
5. Lack of built-in methods: Arrays do not have built-in methods for common
operations like sorting or searching, requiring manual implementation or relying
on external libraries for such functionalities.
11
1.6 Summary
Arrays in Java are a fundamental data structure that offer several advantages
and disadvantages. One of the main advantages of arrays is their efficient
memory usage.
Another advantage of arrays is their ability to provide direct and fast access to
elements through indexing. This allows for quick retrieval and modification of
specific elements without the need to traverse the entire data structure.
Arrays also support simple iteration using standard loops, making it easy to
process each element sequentially.
Arrays have some limitations as well. One significant disadvantage is their
fixed size. Once an array is created, its length cannot be changed, requiring
manual management or the creation of new arrays when the size needs to be
adjusted.
This can lead to inefficient memory usage or the need for frequent resizing in
dynamic scenarios.
Arrays in Java do not provide built-in methods for common operations like
sorting or searching, requiring manual implementation or relying on external
libraries for such functionalities.
Arrays in Java are a powerful data structure with efficient memory usage and
fast element access, but their fixed size and limitations in dynamic scenarios
can be a drawback.
12
1.7 Case Study
Solution:
To implement the sales analytics dashboard, we can utilize arrays to store and
analyze the sales data efficiently.
1.Define the Array Structure:
We can create an array to represent each region and store sales data for each
product. Each element of the array would correspond to a specific region.
3. Perform Analysis: Using the sales data stored in the array, we can perform
various analyses to gain insights into product performance.
Total Sales: Sum up the sales values for each region to determine the overall
sales performance.
Average Sales: Calculate the average sales across regions by dividing the
total sales by the number of regions.
Highest-Selling Product: Identify the region with the highest sales value to
determine the highest-selling product.
For example, using the array above, we can perform the following
calculations:
Total Sales: 150 + 220 + 180 + 300 = 850 thousand
Average Sales: 850 thousand / 4 regions = 212.5 thousand
Highest-Selling Product: Region 4 with 300 thousand sales
These analyses provide valuable insights into the sales performance across
different regions, helping the company make informed decisions and
prioritize efforts for specific products or regions.
13
Visualization:
To present the sales data in an easily understandable format, the company
can create visualizations such as bar charts, line graphs, or pie charts. These
visualizations can display the total sales, average sales, and highest-selling
products for each region, enabling stakeholders to quickly interpret the data
and identify trends or areas of improvement.
By utilizing arrays to store and analyses sales data, the company can
effectively monitor product performance across regions and make data-
driven decisions to optimize sales strategies and resource allocation.
14
1.8 Terminal Questions
1. Explain the process of declaring an array in Java, including the syntax, data type,
and the various ways to initialize an array. Provide examples to illustrate your
explanations.
3. Describe the method or operator used to obtain the length of an array, including
its syntax and return value.
4. How would you sort an array of integers in ascending order in Java? Provide the
code snippet for your solution.
5. Imagine you are working on a game development project. How would you employ
arrays in Java to represent and manage the game board, such as storing the
positions of game characters or recording the state of different game tiles?
15
MCQ QUESTIONS
16
8. How do you access the third element in an array named numbers?
a) numbers[2]
b) numbers[3]
c) numbers(3)
d) numbers.Get(2)
1.9 Answers
1. To solve by student
2. In Java, the default value of an element in an integer array is 0 if it is not explicitly
initialized. When an array of integers is created, each element in the array is assigned a
default value based on its data type. For integers, the default value is 0. This means
that if you do not provide a specific value for an element in an integer array during
initialization, it will automatically be set to 0. It's important to note that other types of
arrays, such as boolean arrays, will have different default values (e.g., false for
booleans) if not explicitly initialized.
3. To solve by student
4. To find the average value of elements in an array in Java, you can follow these
steps:
1. Initialize a variable to hold the sum of all the elements in the array. Let's call it
sum and set it to 0.
2. Iterate over each element in the array using a loop.
3. Add each element to the sum variable.
4. After the loop completes, calculate the average by dividing the sum by the total
number of elements in the array.
5. Optionally, round the average to the desired decimal places if needed.
Here's an example code snippet to demonstrate this:
}
}
Output:
Average: 15.0
Explanation:
The program calculates the average value of the elements in the numbers array.
• The array numbers contains the values: 5, 10, 15, 20, and 25.
• The variable sum is initialized to 0.
• The for loop iterates over each element in the numbers array.
• In each iteration, the current element is added to the sum variable.
• After the loop completes, the average is calculated by dividing the sum by
the length of the numbers array.
• The resulting average, 15.0, is then printed to the console using
System.out.println().
Therefore, the output will be "Average: 15.0".
5. To reverse the order of elements in an array in Java, you can use the following
approach:
1. Determine the midpoint of the array by dividing the length of the array by 2.
2. Iterate over the array from the start index (0) to the midpoint.
3. Swap the elements at the current index with the corresponding element
from the end of the array.
4. Continue swapping elements until you reach the midpoint.
5. The array will be reversed once the swapping is complete.
6. Here's an example code snippet that demonstrates this approach:
19
public class reverse
{
public static void main(String [] args)
{
int[] numbers = {1, 2, 3, 4, 5};
int length = numbers.length;
int midpoint = length / 2;
Output :
54321
Explanation:
The program reverses the order of elements in the numbers array using a loop and
swapping the elements.
20
LONG ANSWER QUESTIONS
In this method, you declare the array with a specific size, and the elements are
initialized to default values based on their data type. For example:
This declares an integer array named numbers with a size of 5. The elements of
the array are initialized to the default value for integers, which is 0.
2 . To solve by student
3. In Java, to obtain the length of an array, you can use the length property of
the array. The length property provides the number of elements present in the
array. Here's the syntax and details regarding its usage:
Syntax:
arrayName.length
Here, arrayName refers to the name of the array for which you want to
determine the length.
Return Value: The length property returns an integer value representing the
number of elements in the array. The length is always a non-negative value.
4. In Java, you can sort an array of integers in ascending order using the
Arrays.sort() method from the java.util package. Here's the code snippet to
accomplish this:
import java.util.Arrays;
21
MCQ QUESTIONS ANSWER
22
1.9 References
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
https://www.baeldung.com/java-arrays-guide#:~:text=According%20to%20the
%20Java%20documentation,a%20variable%20holding%20a%20value
https://jenkov.com/tutorials/java/arrays.html#:~:text=A%20Java%20Array%20is
%20a,array%20later%20in%20this%20text.
23