0% found this document useful (0 votes)
24 views14 pages

Understanding Java Arrays Basics

The document provides a comprehensive overview of arrays in Java, including their definition, features, types (single and multi-dimensional), and how to create and manipulate them. It explains key operations such as searching (linear and binary search) and sorting (bubble sort and exchange selection sort), along with example programs for practical understanding. Additionally, it covers the structure of two-dimensional arrays and the concept of diagonals in square matrices.

Uploaded by

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

Understanding Java Arrays Basics

The document provides a comprehensive overview of arrays in Java, including their definition, features, types (single and multi-dimensional), and how to create and manipulate them. It explains key operations such as searching (linear and binary search) and sorting (bubble sort and exchange selection sort), along with example programs for practical understanding. Additionally, it covers the structure of two-dimensional arrays and the concept of diagonals in square matrices.

Uploaded by

Pradyumn Mishra
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Arrays

An array can be imagined as a collection of variables, all having a common name. Java array is
a collection of elements of a similar data type. In the RAM the elements of an array are stored
in a continuous memory location.

Suppose you have to store marks of 100 students. You will need 100 variables. It will be
difficult to name the variables and to remember the names. With arrays, you can store 10 or
50 or 100 or 1000 etc. values under a single name.

An array can be represented as a series of values arranged serially as shown below.

Features of Arrays

1. Array in Java is index-based. Like in Strings, the first element of the array is stored at the
index Number 0, 2nd element is stored at index no. 2 and so on.
2. An array name is written as: a variable name followed by a set of square brackets [ ].
Suppose our array name if ‘a’, we write the array as a[ ].
3. Like each house of colony is identified by its unique address, similarly each cell of an array
is identified by what is called Cell Reference or Cell Address.
4. The Cell Reference or Cell Address is the name of the array followed by the index number
of the cell in square brackets.
For example: the first element of the array is represented as a[0] (called ‘a of 0’), 2nd
element is a[1] ( called as ‘a of 1’ ) and so on.
5. Like we have the length of a String, we have the size of the array. The size of the array is an
integer (int) value.
To know the number of characters in a String, we have the length() function, and we write:
int len = [Link]();

Similarly to know the number of cells in a array we write as:


int l = [Link];
That is ‘length’ without a set of brackets.

6. IMPORTANT POINT : So it is understood, that the last cell of an array will have the index
number equal to one less than its length( like in Strings).

Need of Arrays:
As a number of values are referred by a single name, it is easier to remember the array names

Types of Arrays
We have Single and MultiDimensional Arrays. MultiDimensional Arrays are 2D and 3D arrays.
We will only work on Single and 2D arrays.

SINGLE DIMENSIONAL ARRAY

Below is an example to Single dimensional array.

The elements or cells are arranged in a line represented horizontally or vertically. Each cell is
referenced by its Cell Address.

DOUBLE DIMENSIONAL ARRAY

Below is an example to Double dimensional array.


Here we have cells arranged in horizontal rows and vertical columns. The index numbers of
rows and columns starts with 0 (Zero). So the cell address consists of the array name followed
by row number and column number as shown above.

Creating ( Declaring )Arrays


You can create or declare an array by using the new operator with the following syntax –
Single Dimension

Syntax
dataType arrayName[] = new dataType[arraySize];
Example : int a[ ] = new int[ 10 ];

Here an array of name ‘a’ is declared of ‘int’ type which is of size 10, that is it can hold 10
integer numbers.

Double Dimension
Syntax
dataType arrayName[][] = new dataType[NoOfRows][NoOfCols];
Example : int m[ ][ ] = new int[ 3 ][ 4 ];

Here an array of name ‘m’ is declared of ‘int’ type which 3 rows and 4 columns.
What is /n and /t ?

First we will work only on SINGLE DIMENSIONAL ARRAYS.

Suppose we have to store natural numbers in an array. We can write:

a[ 0 ] = 1 ;
a[ 1 ] = 2 ;
a[ 2 ] = 3 ;
a[ 3 ] = 4 ;
a[ 4 ] = 5 ;
and so on…..
What happens for 50 or 1000 values? We have to write so many lines….

So instead we write this assignment in a loop as shown in the following example:

Now, a simple question

Q: Write a program to declare an array of size 10, store first 10 Natural Numbers in it, and
print the array.

import [Link].*;
public class arrfirst
{
public static void main(String args[]) throws IOException
{
int a[ ]= new int[10];
int x;
for( x = 0 ; x <= 9 ; x++ )
{
a[x] = x+1;
}

for( x = 0 ; x <= 9 ; x++ )


{
[Link](a[x] + " ");
}
}
}

V Important Note:
In the above example we have used 2 for loops. It can be done in one loop, BUT IT IS NOT
DONE LIKE THAT. It could be done in one loop here, but not possible in other examples of
arrays. As we go on with the examples, you will understand.
Now try this program:
Q. Write a program to declare an array of size 10, input values into it and print the largest and
smallest numbers in the array.

We have two important operations in arrays:


Searching and Sorting.

Searching is done by two types:


Linear Search and Binary Search

Sorting is also done by two types:


Bubble Sort and Exchange Selection Sort.

SEARCHING
As the name suggests, Searching means to input a value (called search value) and look if it is
present in the array. The search value is matched with the cells of the array. If the value is
found, then the search operation is successful, otherwise it fails.

TYPES OF SEARCHING

LINEAR SEARCH:
Here the search value is matched with each and every value in the cells. The matching starts
with the leftmost cell and one-by-one proceeds towards the right cell. If the search value is
found, the operation is stopped and further cells will not be checked. If the search value is not
found in any of the cells, a message ig given as “Search Value not found”.

Concept of Flag in Programming


Flag is not a reserved word, but is a variable used as a signal. It acts as a switch – OFF or ON.
For example in a set of numbers there is a condition, which we know, will be true only for a
single value in that range. First we initialize the value of ‘flag’ to 0 (zero ie OFF). We run the
loop for that range. If that condition is met, we store 1 to ‘flag’ (ie success or ON). At the end
of the loop, we check the value of ‘flag’. If ‘flag’ value is 1, then we know the condition was
met. If the value didn’t change from 0, we know, the condition was never met with.

Program of Linear Search uses the concept of flag.


// Find search Value in an Array
// by Linear Search Technique

import [Link].*;
public class arrlinearsrch
{
public static void main(String args[]) throws IOException
{

int a[]= new int[10]; // Declaring an array


int x, m, flag=0;

Scanner sc = new Scanner([Link]);


[Link]("Enter 10 values ... ");

for(x=0; x<=9; x++)


{
a[x]=[Link](); // Inputting values
into the array
}

[Link]("Enter number to searched ");


m=[Link]();

for(x=0; x<=9; x++)


{
if(a[x] == m)
{
flag=1;
break;
}
}
if(flag==1)
[Link]("Number found at position : "+ x+1);
else
[Link]("Sorry. Search Value NOT Found");
}
}

BINARY SEARCH
The most important condition for this type of search is the array should be sorted, that is the
values of the array must be arranged in either the ascending or descending order.
In this type of search, the array is divided into two (binary is two) halves. The leftmost cell is
the Lower value (denoted by L), and the rightmost cell is the Upper value (denoted by U). The
center cell is the Middle cell (denoted by M).

Search Method: First search value is compared with the middle cell. If it is there, our search is
successful.
If the search value is less than the item in the middle cell, it means that our value lies in the
left half. (Because the array is sorted). Consequently the cells in the right half are ignored
because the values will not be there.
Similarly, if the search value is more than the item in the middle cell, it means that our value
lies in the right half. (Because the array is sorted). Consequently the cells in the left half are
ignored because the values will not be there.

// Program to depict the usage of Binary Search Technique.


// It is assumed that the list of numbers in an array is stored in
// ascending order.

import [Link].*;
class binsearch3
{
public static void main(String args[]) throws IOException
{
int num[] =new int[10];
int m,L,U,mid=0,pos;

Scanner sc = new Scanner([Link]);


[Link]("\nEnter any ten numbers as elements of an array in");
[Link](" ascending order ");
for (int i=0;i<10;i++)
{
num[i]=[Link]();
}
[Link]("Enter number to searched ");
m=[Link]();
L = 0;
U = 9;
pos = -1;
int flag=0;
while ((L<= U))
{
mid = (L+U)/2;
if (num[mid] == m)
{
flag=1;
break;
}
else
if (num[mid]<m)
L = mid + 1;
else
U = mid - 1;
}
if (flag==1)
{
[Link]("The element "+m+" lies in the array");
[Link](" at "+ (mid+1) +" position");
}
else
[Link]("The element does not lie in the array");
}
}

SORTING
Sorting means to arrange the values in a certain order, either ascending or descending.

BUBBLE SORT TECHNIQUE

Visualization
[Link]
Bubble sort is an algorithm that compares the adjacent elements and swaps their positions if
they are not in the intended order. The order can be ascending or descending.
How Bubble Sort Works?
Starting from the first index, compare the first and the second elements. If the first element is
greater than the second element, they are swapped.

Now, compare the second and the third elements. Swap them if they are not in order.

The above process goes on until the last element.

The same process goes on for the remaining iterations. After each iteration, the largest
element among the unsorted elements is placed at the end.
In each iteration, the comparison takes place up to the last unsorted element.

The array is sorted when all the unsorted elements are placed at their correct positions.

EXCHANGE SELECTION SORT TECHNIQUE

2D ARRAYS
Now let’s see the two dimensional arrays in detail. 2D arrays are also referred to as Matrices
(Matrix). We will call then DDA (Double Dimensional Array).
2D Arrays can be of following types:
SQUARE ARRAYS: Here the number of rows will be equal to number of columns.
RECTANGULAR ARRAYS: Here the number of rows and number of columns will be unequal.
As there are rows and columns in 2D arrays, we need nested loops for access the array.
In 2D arrays, we don’t say length, but we say size of the array.
For example, if we say size of the 2D array is 10x20 ( said as 10 by 20 ), it means the array has
10 rows and 20 columns. This array will be written as a[10][20].

Q: Write a program to declare an DDA of size 4x5, store Natural Numbers in it, and print the
array.

import [Link].*;
public class arrfirst
{
public static void main(String args[]) throws IOException
{
int a[][]= new int[4][5];
int r, c, t=1;
for( r = 0 ; r <= 3 ; r++ )
{
for( c = 0 ; c <= 4 ; c++ )
{
a[r][c] = t++;
}
}

for( r = 0 ; r <= 3 ; r++ )


{
for( c = 0 ; c <= 4 ; c++ )
{
[Link](a[r][c] + "\t");
}
}
}
}
DIAGONALS OF SQUARE MATRIX:
A square matrix has two diagonals.
Left Diagonal and Right Diagonal

Left Diagonal
The cell references of the left diagonal:
1. The row index is equal to the column index.
2. The cells above the left diagonal will have row index less than column index.
3. The cells below the left diagonal will have row index more than column index.

Right Diagonal
The cell references of the right diagonal:
1. The sum of the row index and column index is equal to the number of rows/columns minus
one.
2. The cells above the right diagonal will have sum of the row and column index less than
number of rows/columns minus one.
3. The cells above the right diagonal will have sum of the row and column index greater than
number of rows/columns minus one.
This is a table which shows the relation for the cells above, below, on and above,
on and below or on the Left and the Right diagonals:

Common questions

Powered by AI

Single-dimensional arrays allocate memory in a contiguous linear manner, allowing for efficient indexing and operation due to the predictable relationship between element position and memory address. This linearity makes single-dimensional arrays optimal for situations with straightforward data access requirements. In contrast, two-dimensional arrays, while also stored linearly in memory, require an additional computation step for memory address calculation involving multiplying indices and row or column sizes, which could slightly impact performance. However, the structure of 2D arrays supports more complex or dimensionally natural data modeling. For application design, choosing between the two depends on the complexity of the data relationships and performance needs, as working with 2D arrays can introduce complexity in traversal and manipulation compared to 1D arrays but is better suited for multi-level data interactions like matrices or grids .

Multidimensional arrays are advantageous in scenarios that require the representation of data in a grid-like structure. Such use cases include storing data for mathematical matrices, representing game boards such as chess, or handling image data, where each element requires both a row and column descriptor. The structure of multidimensional arrays, particularly 2D arrays, allows for easy access and manipulation of this grid format, as it enables direct indexing using row and column numbers. These properties make them suitable for situations where relationships between data are naturally two-dimensional or complex and require simultaneous row-column association .

Single-dimensional arrays consist of elements stored in a linear sequence, and each element is accessed via a single index. They are best used for simple lists like student scores or names where data naturally fits a single line. In contrast, two-dimensional arrays, or matrices, store data in a grid akin to a table, requiring two indices to access an element (one for the row and one for the column). This structure is useful for representing more complex data relationships such as tables in a spreadsheet, board games, or pixel data in images. The implementation of two-dimensional arrays involves nested loops for iteration over rows and columns, adding complexity but also versatility for multi-dimensional data manipulation .

Understanding cell references in two-dimensional arrays is crucial for correctly accessing and manipulating data within a matrix. Each element in a 2D array is accessed using two indices corresponding to its row and column, which simulate grid coordinates. This understanding is essential for implementing matrix operations such as transposition, addition, and multiplication, where specific elements need to be efficiently and accurately targeted. Proper use of row and column indices enhances performance and accuracy in these operations, making the management of multi-dimensional data intuitive and preventing logical errors in algorithm implementation .

In Java, using the "new" keyword in array declaration allocates memory dynamically for the array. This is crucial because it allows for runtime determination of array size, meaning the exact amount of required memory can be allocated when the size of the array is not known at compile time. This is particularly important for large datasets as it leads to efficient memory management, reducing waste and allowing for the flexibility of allocation on the heap. However, care must be taken with large datasets to ensure that sufficient memory is available, as dynamic allocation might also lead to runtime exceptions if the system runs out of memory .

A flag variable in linear search serves as a signal or switch to indicate whether the search value has been found within the array. Initially, the flag is set to a default state, often 0 (OFF), which represents that the search value has not been found. As the search algorithm iterates through the elements, if it encounters the search value, the flag is set to 1 (ON). The presence of a flag allows the program to exit early from the loop upon finding the match, thus optimizing the operation slightly by avoiding unnecessary checks after finding the value. It also simplifies the decision-making process after the loop by checking the flag to determine if the value was found, streamlining the output reporting .

The binary search algorithm compares the target search value to the middle element of a sorted array. If the middle element matches the search value, the search is successful. If the search value is less than the middle element, the algorithm discards the right half of the array because all elements there are larger. Conversely, if the search value is greater, it discards the left half. This divide-and-conquer strategy significantly reduces the number of elements to examine in each step, narrowing the search space logarithmically. As a result, binary search has a time complexity of O(log n), making it much more efficient than linear search for large, sorted datasets, which require O(n) operations .

Linear search and binary search are both used to find elements in arrays but differ significantly in approach and efficiency. Linear search does not require the array to be sorted; it simply checks each element sequentially until it finds the match or reaches the end of the array, with a time complexity of O(n) where n is the number of elements. In contrast, binary search requires the array to be sorted beforehand. It repeatedly divides the array in half and compares the middle element with the target value, reducing the search interval by half each time. This results in a much faster time complexity of O(log n). Therefore, while linear search is simpler and more versatile as it works with unsorted arrays, binary search is substantially more efficient for large, sorted datasets .

Contiguous memory allocation for arrays means that all elements of the array are stored sequentially in adjacent memory locations. This design facilitates efficient data access as the CPU can easily compute the address of any element using the base address along with an index offset, which is a simple and fast operation. This is particularly beneficial for performance in terms of speed and caching since the elements are likely to be loaded into the memory cache due to the locality of reference. Furthermore, this contiguous allocation allows for more efficient use of memory and simpler computation for iteration, both crucial for operations like sorting and searching within the array .

Bubble sort is simple to implement and understand, suitable for educational purposes or small datasets where its performance is not critical. However, bubble sort is generally inefficient for large datasets, as it has a time complexity of O(n^2) due to repetitive comparisons and swaps. This can make it much slower compared to more advanced algorithms. Compared to bubble sort, the exchange selection sort also generally sorts with O(n^2) complexity but tends to perform fewer swaps since it specifically selects the minimum or maximum for swap per pass. While both bubble and exchange selection sorts are not typically used in professional contexts beyond teaching, their simplicity makes them easily understandable to beginners .

You might also like