0% found this document useful (0 votes)
7 views11 pages

Java Arrays: Basics and Operations

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)
7 views11 pages

Java Arrays: Basics and Operations

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

UNIT III

ARRAYS

An array is a collection of similar type of elements which has contiguous memory location.
The elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.
Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime.
Syntax to Declare an Array in Java
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
Ex: int a[]={33,3,4,5};//declaration, instantiation and initialization

Storage of Array in Computer Memory,

Access Elements by Index:


Array indices start at 0. So, numbers[0] accesses the first element, numbers[1] the second, and so
on.
Java

[Link](numbers[0]); // Outputs 10
[Link](numbers[1]); // Outputs 20

Operations on Array Elements

Get the First and Last Element of an Array


This is one of the most common and simple tasks thanks to the access-by-index nature of
[Link]’s start by declaring and initializing an int array that will be used in all our examples
(unless we specify otherwise):
int[] array = new int[] { 3, 5, 2, 5, 14, 4 };
Knowing that the first item of an array is associated with the index value 0 and that it has a
length attribute that we can use, then it’s simple to figure out how we can get these two elements:

int firstItem = array[0];


int lastItem = array[[Link] - 1];
Get a Random Value from an Array
By using the [Link] object we can easily get any value from our array:
int anyValue = array[new Random().nextInt([Link])];
Append a New Item to an Array
int[] newArray = [Link](array, [Link] + 1);
newArray[[Link] - 1] = newItem;
int[] newArray = [Link](array, newItem);
As we can imagine, this method doesn’t modify the original array object; we have to assign its
output to a new variable.
Insert a Value Between Two Values
Because of its indexed-values character, inserting an item in an array between two others is not a
trivial job.
int[] largerArray = [Link](2, array, 77);
Compare Two Arrays
Even though arrays are Objects and therefore provide an equals method, they use the default
implementation of it, relying only on reference equality.

We can anyhow invoke the [Link]‘ equals method to check if two array objects contain
the same values:
boolean areEqual = [Link](array1, array2);
Check if an Array Is Empty
This is an uncomplicated assignment having in mind that we can use the length attribute of
arrays:
boolean isEmpty = array == null || [Link] == 0;
Moreover, we also have a null-safe method in the ArrayUtils helper class that we can use:
boolean isEmpty = [Link](array);
Remove Duplicates from an Array
The easiest way of removing duplicates is by converting the array to a Set implementation.
As we may know, Collections use Generics and hence don’t support primitive types.
For this reason, if we’re not handling object-based arrays as in our example, we’ll first need to
box our values:

Integer[] list = [Link](array);


// Remove duplicates
Set<Integer> set = new HashSet<Integer>([Link](list));
// Create array and unbox
return [Link]([Link](new Integer[[Link]()]));
Program to copy all elements of one array into another array

public class CopyArray {


public static void main(String[] args) {
//Initialize array
int [] arr1 = new int [] {1, 2, 3, 4, 5};
//Create another array arr2 with size of arr1
int arr2[] = new int[[Link]];
//Copying all elements of one array into another
for (int i = 0; i < [Link]; i++) {
arr2[i] = arr1[i];
}
//Displaying elements of array arr1
[Link]("Elements of original array: ");
for (int i = 0; i < [Link]; i++) {
[Link](arr1[i] + " ");
}

[Link]();

//Displaying elements of array arr2


[Link]("Elements of new array: ");
for (int i = 0; i < [Link]; i++) {
[Link](arr2[i] + " ");
}
}
}
Output:

Elements of original array


12345
Elements of new array:
12345

Dynamic array
The dynamic array is a variable size list data structure. It grows automatically when we try to
insert an element if there is no more space left for the new element. It allows us to add and
remove elements. It allocates memory at run time using the heap. It can change its size during
run time.

In Java, the dynamic array has three key features: Add element, delete an element, and resize an
array.

Add Element in a Dynamic Array


In the dynamic array, we can create a fixed-size array if we required to add some more elements
in the array. Usually, it creates a new array of double size. After that, it copies all the elements to
the newly created array. We use the following approach:
Delete an Element from a Dynamic Array

If we want to remove an element from the array at the specified index, we use the removeAt(i)
method. The method parses the index number of that element which we want to delete. After
deleting the element, it shifts the remaining elements (elements that are right to the deleted
element) to the left from the specified index number. We also use the remove() method that
deletes an element from the end of the array. After shifting the elements, it stores 0 at the palace
of the last element. Let's understand it through an example, as we have shown in the following
figure.

Resizing a Dynamic Array in Java

We need to resize an array in two scenarios if:


The array uses extra memory than required.
The array occupies all the memory and we need to add elements.
In the first case, we use the srinkSize() method to resize the array. It reduces the size of the array.
It free up the extra or unused memory. In the second case, we use the growSize() method to
resize the array. It increases the size of the array.

It is an expensive operation because it requires a bigger array and copies all the elements from
the previous array after that return the new array.

public class DynamicArrayExample1


{
private int array[];
private int count;
private int sizeofarray;
//creating a constructor of the class that initializes the values
public DynamicArrayExample1()
{
array = new int[1];
count = 0;
sizeofarray = 1;
}
//creating a function that appends an element at the end of the array
public void addElement(int a)
{
//compares if the number of elements is equal to the size of the array or not
if (count == sizeofarray)
{
//invoking the growSize() method that creates an array of double size
growSize();
}
//appens an element at the end of the array
array[count] = a;
count++;
}
//function that creates an array of double size
public void growSize()
{
//declares a temp[] array
int temp[] = null;
if (count == sizeofarray)
{
//initialize a double size array of array
temp = new int[sizeofarray * 2];
{
for (int i = 0; i < sizeofarray; i++)
{
//copies all the elements of the old array
temp[i] = array[i];
}
}
}
array = temp;
sizeofarray= sizeofarray * 2;
}
//creating a function that deletes an element at the specified index
public void addElementAt(int index, int a)
{
//compare the size with the number of elements if not equal grows the array size
if (count == sizeofarray)
{
//invoking growSize() method
growSize();
}
for (int i = count - 1; i >= index; i--)
{
//shifting all the elements to the left from the specified index
array[i + 1] = array[i];
}
//inserts an element at the specified index
array[index] = a;
count++;
}
public static void main(String[] args)
{
DynamicArrayExample1 da = new DynamicArrayExample1();
//adding elements to the array
[Link](12);
[Link](22);
[Link](35);
[Link](47);
[Link](85);
[Link](26);
[Link](70);
[Link](81);
[Link](96);
[Link](54);
[Link]("Elements of the array:");
//iterate over the array for accessing the elements
for (int i = 0; i < [Link]; i++)
{
[Link]([Link][i] + " ");
}
[Link]();
//determines and prints the size and number of elements of the array
[Link]("Size of the array: " + [Link]);
[Link]("No. of elements in the array: " + [Link]);
//invoking the method to add an element at the specified index
[Link](5, 99); //where 5 is the index number and 99 is the element to be add
[Link]("\nElements of the array after adding an element at index 5:");
//iterate over the array for accessing the elements after adding the element at index 5
for (int i = 0; i < [Link]; i++)
{
[Link]([Link][i] + " ");
}
[Link]();
//determines and prints the size and number of elements of the array
[Link]("Size of the array: " + [Link]);
[Link]("No. of elements in the array: " + [Link]);
}
}

Sort an Array
The sorting is a way to arrange elements of a list or array in a certain order. The order may be in
ascending or descending order. The numerical and lexicographical (alphabetical) order is a
widely used order.

In this section, we will learn how to sort array in Java in ascending and descending order using
the sort() method and without using the sort() method. Along with this, we will also learn how to
sort subarray in Java.
Using the sort() Method
In Java, Arrays is the class defined in the [Link] package that provides sort() method to sort an
array in ascending order. It uses Dual-Pivot Quicksort algorithm for sorting. Its complexity is
O(n log(n)). It is a static method that parses an array as a parameter and does not return anything.
We can invoke it directly using the class name. It accepts an array of type int, float, double, long,
char, byte
[Link]

import [Link];
public class SortArrayExample1
{
public static void main(String[] args)
{
//defining an array of integer type
int [] array = new int [] {90, 23, 5, 109, 12, 22, 67, 34};
//invoking sort() method of the Arrays class
[Link](array);
[Link]("Elements of array sorted in ascending order: ");
//prints array using the for loop
for (int i = 0; i < [Link]; i++)
{
[Link](array[i]);
}
}
}
Output:

Array elements in ascending order:


5
12
22
23
34
67
90
109
Searching Elements in an Array | Array Operations
Last Updated : 23 May, 2024
In this post, we will look into search operation in an Array, i.e., how to search an element in an
Array, such as:

Searching in an Unsorted Array using Linear Search


Searching in a Sorted Array using Linear Search
Searching in a Sorted Array using Binary Search
Searching in an Sorted Array using Fibonacci Search
Searching operations in an Unsorted Array using Linear Search

// Function to implement search operation


int findElement(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;

// If the key is not found


return -1;
}

// Driver's Code
int main()
{
int arr[] = { 12, 34, 10, 6, 40 };
int n = sizeof(arr) / sizeof(arr[0]);

// Using a last element as search element


int key = 40;

// Function call
int position = findElement(arr, n, key);

if (position == -1)
printf("Element not found");
else
printf("Element Found at Position: %d",
position + 1);

return 0;
}

Output
Element Found at Position: 5

Types of Array in java


There are two types of array.
o Single Dimensional Array
o Multidimensional Array
Single Dimensional Array
Syntax to Declare an Array in Java

dataType[] arr; (or)


dataType []arr; (or)
dataType arr[];
Instantiation of an Array in Java

arrayRefVar=new datatype[size];

//Java Program to illustrate how to declare, instantiate, initialize


//and traverse the Java array.
class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<[Link];i++)//length is the property of array
[Link](a[i]);
}}

Output:

10
20
70
40
50

Multidimensional Array in Java


In such case, data is stored in row and column based index (also known as matrix form).
Syntax to Declare Multidimensional Array in Java

dataType[][] arrayRefVar; (or)


dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column

//Java Program to illustrate the use of multidimensional array


class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
[Link](arr[i][j]+" ");
}
[Link]();
}
}}

Output:

123
245
445

You might also like