JavaUNIT-3.1
JavaUNIT-3.1
Arrays
Arrays in Java are fundamental data structures used to store and manipulate collections of
elements of the same type.
They provide efficient ways to access and manage data, making them essential for various
programming tasks.
What is an Array in Java?
An array refers to a data structure that contains homogeneous elements. This means that all
the elements in the array are of the same data type. Let's take an example:
For example, if we want to store the names of 100 people then we can create an array of the
string type that can store 100 names.
String[] array = new String[100];
Here, the above array cannot store more than 100 names. The number of values in a Java
array is always fixed.
There are three main features of an array:
Dynamic allocation: In arrays, the memory is created dynamically, which reduces the
amount of storage required for the code.
Elements stored under a single name: All the elements are stored under one name.
This name is used any time we use an array.
Occupies contiguous location: The elements in the arrays are stored at adjacent
positions. This makes it easy for the user to find the locations of its elements.
Advantages of Arrays in Java
• Java arrays enable you to access any element randomly with the help of indexes
• It is easy to store and manipulate large data sets
Disadvantages of Arrays in Java
• The size of the array cannot be increased or decreased once it is declared—arrays
have a fixed size
• Java cannot store heterogeneous data. It can only store a single type of primitives
• declare an array.
Syntax:
In Java, here is how we can declare an array.
dataType[] arrayName;
dataType - it can be primitive data types like int, char, double, byte, etc. or Java objects
arrayName - it is an identifier
To mention the size of the array
Array_ref = new datatype[size];
How to Initialize Arrays in Java?
In Java, we can initialize arrays during declaration. For example,
//declare and initialize and array
int[] age = {12, 4, 5, 2, 5};
Here, we have created an array named age and initialized it with the values inside the
curly brackets.
// create an array
int[] age = {12, 4, 5, 2, 5};
// access each array elements
System.out.println("Accessing Elements of Array:");
System.out.println("First Element: " + age[0]);
System.out.println("Second Element: " + age[1]);
System.out.println("Third Element: " + age[2]);
System.out.println("Fourth Element: " + age[3]);
System.out.println("Fifth Element: " + age[4]);
}
}
//Example: Looping Through Array Elements
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};
// loop through the array
// using for loop
System.out.println("Using for Loop:");
for(int i = 0; i < age.length; i++) {
System.out.println(age[i]);
}
}}
//Example: Using the for-each Loop
class Main {
public static void main(String[] args) {
// create an array
int[] age = {12, 4, 5};
// loop through the array
// using for loop
System.out.println("Using for-each Loop:");
for(int a : age) {
System.out.println(a);
}}
}
We can copy array elements from one array into another array. They are as follows:
1. Using for loop to copy individual elements one by one.
2. Using the static arraycopy() method provided by the System class.
3. Using the clone method to copy arrays.
//Using for loop to Copy Individual Elements One by One:
public class CopyArrayUsingLoop
{
public static void main(String[] args)
{
// Create an array of six integer elements.
int[ ] originalArray = {2, 3, 4, 5, 6, 7};
// Create an array newArray[] of same size as originalArray[].
int[ ] newArray = new int[originalArray.length];
1. One-dimensional Array
Also known as a linear array, the elements are stored in a single row.
One Dimensional Array is always used with only one subscript([]). A one-dimensional array
behaves likes a list of variables.
One dimensional array represents one row or one column of array elements that share a
common name and is distinguishable by index values.
For example:
//Simple example program where we will create one dimensional array of five elements
and read its elements by using for loop and display them one by one.
• A matrix is a group of elements arranged into many rows and columns. We can use
two dimensional array to store elements of a matrix or table.
//Example program for 2-dimensional array
import java.util.Scanner;
public class ArrayInputExample2
{
public static void main(String args[])
{
int m, n, i, j;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of rows: ");
//taking row as input
m = sc.nextInt();
System.out.print("Enter the number of columns: ");
//taking column as input
n = sc.nextInt();
// Declaring the two-dimensional matrix
int array[][] = new int[m][n];
// Read the matrix values
System.out.println("Enter the elements of the array: ");
//loop for row
for (i = 0; i < m; i++)
//inner for loop for column
for (j = 0; j < n; j++)
array[i][j] = sc.nextInt();
//accessing array elements
System.out.println("Elements of the array are: ");
for (i = 0; i < m; i++)
{
for (j = 0; j < n; j++)
//prints the array elements
System.out.print(array[i][j] + " ");
//throws the cursor to the next line
System.out.println();
}
}
}
3. Multi-dimensional Array
This is a combination of two or more arrays or nested arrays. We can even use more than two
rows and columns using the following code:
Syntax to Declare Multidimensional Array
dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array
int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array
arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
class DuplicateElement
{
public static void main(String[] args)
{
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};
System.out.println("Duplicate elements in given array: ");
//Searches for duplicate element
for(int i = 0; i < arr.length; i++)
{
for(int j = i + 1; j < arr.length; j++)
{
if(arr[i] == arr[j])
System.out.println(arr[j]);
}
}
}
}
//Program to print the elements of an array in reverse order
class ReverseArray
{
public static void main(String[] args)
{
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
System.out.println("Original array: ");
for (int i = 0; i < arr.length; i++)
{
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("Array in reverse order: ");
//Loop through the array in reverse order
for (int i = arr.length-1; i >= 0; i--)
{
System.out.print(arr[i] + " ");
}
}
}
//Java Program to print Odd and Even Numbers from an Array
class OddEvenInArrayExample
{
public static void main(String args[])
{
int a[]={1,2,5,6,3,2};
System.out.println("Odd Numbers:");
for(int i=0;i<a.length;i++)
{
if(a[i]%2!=0)
{
System.out.println(a[i]);
}
}
System.out.println("Even Numbers:");
for(int i=0;i<a.length;i++)
{
if(a[i]%2==0)
{
System.out.println(a[i]);
}
}
}
}
A matrix is said to be sparse matrix if most of the elements of that matrix are 0. It implies that
it contains very less non-zero elements.
To check whether the given matrix is the sparse matrix or not, we first count the number of
zero elements present in the matrix. Then calculate the size of the matrix. For the matrix to be
sparse, count of zero elements present in an array must be greater than size/2.
//Initialize matrix a
int a[][] = {
{4, 0, 0},
{0, 5, 0},
{0, 0, 6}
};
//Calculates number of rows and columns present in given matrix
rows = a.length;
cols = a[0].length;
• The most common way to achieve dynamic array functionality is by using the
ArrayList class from the java.util package. ArrayList is a resizable array
implementation that automatically adjusts its size as needed to accommodate new
elements.
• 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.
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.
Now, the underlying array has a length of five. Therefore, the length of the dynamic array
size is 5 and its capacity is 10. The dynamic array keeps track of the endpoint.
Features of Dynamic Array
In Java, the dynamic array has three key features: Add element, delete an element, and
resize an array.
Suppose in the above array, it is required to add six more elements and, in the array, no more
memory is left to store elements. In such cases, we grow the array using
the growSize() method
//Dynamic change of array size example program
import java.util.ArrayList;
public class DynamicArrayExample
{
public static void main(String[] args)
{
// Create an ArrayList to store integers
ArrayList<Integer> numbers = new ArrayList<>();
// Add elements dynamically
numbers.add(10);
numbers.add(20);
numbers.add(30);
// Print the elements
System.out.println("Elements in the array:");
for (Integer number : numbers)
{
System.out.print(number + " ");
}
System.out.println();
// Add more elements
numbers.add(40);
numbers.add(50);
// Print the updated array
System.out.println("Updated array:");
for (Integer number : numbers)
{
System.out.print(number + " ");
}
}
}
//Example-2
import java.util.ArrayList;
public class DynamicArrayExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
// Add elements dynamically
names.add("Abc");
names.add(“Xyz");
names.add(“Efg");
// Insert an element at a specific index
names.add(1, "Eve");
// Remove an element
names.remove(2);
// Access elements by index
System.out.println(names.get(0));
// Iterate over elements
for (String name : names)
{
System.out.println(name);
}
}
}
Arrays class
• The Arrays class in java.util package. This class provides static methods to
dynamically create and access Java arrays. It consists of only static methods and the
methods of Object class. The methods of this class can be used by the class name
itself.
Methods in Java Array Class
• The Arrays class of the java.util package contains several static methods that can be
used to fill, sort, search, etc in arrays.
• binarySearch()
• equals(array1, array2)
• sort(originalArray)
• sort(originalArray, fromIndex, endIndex)
• copyOf(originalArray, newLength)
• copyOfRange(originalArray, fromIndex, endIndex)
• equals(array1, array2)
• fill(originalArray, fillValue)
// Java Program to Demonstrate Arrays Class Via binarySearch()
method
import java.util.Arrays;
// Main class
public class GFG
{
Arrays.sort(intArr);
import java.util.Arrays;
import java.util.Arrays;
import java.util.Arrays;
import java.util.*;
public class VectorExample {
public static void main(String args[]) {
//Create a vector
Vector<String> vec = new Vector<String>();
//Adding elements using add() method of List
vec.add("Tiger");
vec.add("Lion");
vec.add("Dog");
vec.add("Elephant");
//Adding elements using addElement() method of Vector
vec.addElement("Rat");
vec.addElement("Cat");
vec.addElement("Deer");
//Example-2
import java.util.*;
public class VectorExample2 {
public static void main(String args[]) {
//Create an empty Vector
Vector<Integer> in = new Vector<>();
//Add elements in the vector
in.add(100);
in.add(200);
in.add(300);
in.add(200);
in.add(400);
in.add(500);
in.add(600);
in.add(700);
//Display the vector elements
System.out.println("Values in vector: " +in);
//use remove() method to delete the first
occurence of an element
System.out.println("Remove first occourence of element 200: "+in.remove((Integer)200));
//Display the vector elements afre remove() method
System.out.println("Values in vector: " +in);
//Remove the element at index 4
System.out.println("Remove element at index 4: " +in.remove(4));
System.out.println("New Value list in vector: " +in);
//Remove an element
in.removeElementAt(5);
//Checking vector and displays the element
System.out.println("Vector element after removal: " +in);
//Get the hashcode for this vector
System.out.println("Hash code of this vector = "+in.hashCode());
//Get the element at specified index
System.out.println("Element at index 1 is = "+in.get(1));
}
}