0% found this document useful (0 votes)
11 views25 pages

JavaUNIT-3.1

Uploaded by

sunanda17battu
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)
11 views25 pages

JavaUNIT-3.1

Uploaded by

sunanda17battu
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
You are on page 1/ 25

UNIT-3

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.

How to Access Elements of an Array in Java?


We can access the element of an array using the index number. Here is the syntax for
accessing elements of an array,
// access array elements
array[index]
//Example: Access Array Elements
class Main {
public static void main(String[] args) {

// 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);
}}
}

//Compute Sum and Average of Array Elements


class Main {
public static void main(String[] args) {
int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};
int sum = 0;
Double average;

// access all elements using for each loop


// add each element in sum
for (int number: numbers) {
sum += number;
}
// get the total number of elements
int arrayLength = numbers.length;
// calculate the average
// convert the average from int to double
average = ((double)sum / (double)arrayLength);
System.out.println("Sum = " + sum);
System.out.println("Average = " + average);
}
}
Assigning array to another array
• To copy elements of one array into another array in Java, we have to copy the array’s
individual elements into another array.
• we can use an assignment operator (=) to copy primitive data type variables, but not
arrays are copied using the assignment operator.
• Assigning one array variable to another array variable actually copies one object
reference to another and makes both reference variables point to the same memory
location.
• For example:
• array2 = array1;
• This statement does not copy elements of the array referenced (i.e. pointed) by array1
to array2. It merely copies the reference value from array1 to array2 because array
variables do not themselves hold array elements. They hold a reference to the actual
array.

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

// Copy array elements from originalArray[] into newArray[].


for (int i = 0; i < originalArray.length; i++)
newArray[i] = originalArray[i];
System.out.println("Elements of originalArray[]: ");
for (int i = 0; i < originalArray.length; i++)
System.out.print(originalArray[i] + " ");
System.out.println("\n\nElements of newArray[]: ");
for (int i = 0; i < newArray.length; i++)
System.out.print(newArray[i] + " ");
}
}
OUTPUT:
Elements of originalArray[]:
234567
Elements of newArray[]:
234567
Using System.arraycopy() Method:
• The second way to copy elements of an array to another array is by using arraycopy()
method provided by the System class.
syntax to declare arraycopy() method
public static void arraycopy(Object sourceArray, int srcPos, Object targetArray, int
tarPos, int length);
• sourceArray specifies the name of source array.
• srcPos represents the starting position in the source array from where elements of the
source array will be copied to the target array.
• targetArray specifies the name of target array.
• tarPos represents the starting position in the target array from where new elements
from source array will be copied. If any array elements of target array are present at
that location, it will be overridden by the elements of source array.
• length represents the total number of elements of the source array that are to be copied
into the target array.
• The arraycopy() method does not allocate memory location for the target array. The
target array must have already created with its memory location allocated. After the
copying takes place, targetArray and sourceArray both contain the same elements
with different memory locations.
//example program where we will copy array elements from one array into another
array using arraycopy() method.
public class CopyArrayUsingArraycopy
{
public static void main(String[] args)
{
// Create an array of seven char elements.
char[ ] sourceArray = {‘J’, 'A', ‘V', 'A'};
// Create an array targetArray[] of same size as sourceArray[ ].
char[ ] targetArray = new char[sourceArray.length];
// Copy array elements from sourceArray[ ] into targetArray[ ].
System.arraycopy(sourceArray, 0, targetArray, 0,4 );

System.out.println("Elements of sourceArray[]: ");


for (int i = 0; i < sourceArray.length; i++)
System.out.print(sourceArray[i] + " ");
System.out.println("\n\nElements of targetArray[]: ");
for (int i = 0; i < targetArray.length; i++)
System.out.print(targetArray[i] + " ");
}
}
OUTPUT:
Elements of sourceArray[]:
J AVA
Elements of targetArray[]:
J AVA
Using clone() Method to Copy Array:
//example program where we will copy array elements from one array to another array
by using clone() method.
public class CopyArrayUsingClone
{
public static void main(String[] args)
{
char[ ] Array1 = {‘J’, ‘A’, ‘V’, “A’};
// Copying char array elements from Array1[ ] into Array2[] using clone method.
char[ ] Array2 = Array1.clone();

System.out.println("Elements of Array1[]: ");


for (int i = 0; i < Array1.length; i++)
System.out.print(Array1[i] + " ");
System.out.println("\n\nElements of Array2[]: ");
for (int i = 0; i < Array2.length; i++)
System.out.print(Array2[i] + " ");
}
}
OUTPUT:
Elements of Array1[]:
J AVA
Elements of Array2[]:
J AVA
Types of Arrays
There are three types of arrays. We use these types of arrays as per the requirement of the
program. These are:

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.

public class OneDArr


{
public static void main(String[] args)
{
// Declare and initialize an array of five integer values.
int arr[] = {2, 4, 6, 8, 10};

// Display all five elements on the console.


for (int i = 0; i < arr.length; i++)
System.out.println(arr[i] + " ");
}
}
//Java program in which we will find the length of an array.
public class OneDArr
{
public static void main(String[] args)
{
// Declare and initialize an array of five integer values.
int[ ] num = {2, 4, 6, 8, 10, 12, 14};

// Display the length of array.


System.out.println("Length of array: " +num.length);
}
}
//Example Program using Scanner class to take the input from the keyboard.
import java.util.Scanner;
public class OneDArr {
public static void main(String[] args)
{
// Create an object of Scanner class to take input from the keyboard.
Scanner sc = new Scanner(System.in);

// Ask in how many subjects have you given exams.


System.out.println("In how many subject have you given exams?");
int n = sc.nextInt();

// Create one-dimensional array with size n.


int[ ] marks = new int[n];
System.out.println("Enter your marks obtained in subjects:");
// Store elements into the array using for loop.
for(int i = 0; i < n; i++) {
marks[i] = sc.nextInt();
}
// Find the total marks obtained in subjects.
int total = 0;
for(int i = 0; i < n; i++) {
total += marks[i]; // Or, total = total + marks[i].
}
// Display the total marks on the console.
System.out.println("Total marks: " +total);

// Find the percentage.


float percentage = (float)total/n; // Casting.
System.out.println("Percentage: " +percentage+ "%");
}
}
//A simple Java program in which we will calculate the sum and average of six numbers.
public class OneDArr
{
public static void main(String[] args)
{
int[ ] num = new int[6];
num[0] = 20;
num[1] = 30;
num[2] = 40;
num[3] = 50;
num[4] = 60;
num[5] = 70;
double avg = 0.0;
int sum = 0;
// Find the sum of these numbers.
for(int i = 0; i < 6; i++)
sum = sum + num[i];
avg = (double)sum/6;
System.out.println("Sum of six numbers: " +sum);
System.out.println("Average of six numbers: " +avg);
}
}
/* Program to illustrate creating an array of integers, put some values in the array and
prints each value to standard output*/
class ArrayEx
{
public static void main(String[] args)
{
int[] arr; //declares an array
arr=new int[5]; // allocating memory for 5 integers.
arr[0]=10; // initialise the first elements of the array
arr[1]=20;
arr[2]=30;
arr[3]=40;
arr[4]=50;
for(int i=0;i<arr.length;i++) //accessing the elements of the
specified array
System.out.println(“Element at index” +i+ “:” +arr[i]);
}
}
2. Two-dimensional Array
Two-dimensional arrays store the data in rows and columns:

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

//Example program for multi dimensional array


class MultiDimensional
{
public static void main(String[] args)
{
int arr[][]={{1,2,3},{4,5,6},{7,8,9}};
System.out.println("Displaying elements of 2D array in a matrix form:");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.println(arr[i][j]+” “);
}
System.out.println();
}
}
}
//Java Program to demonstrate the addition of two matrices in Java
class MatrixAdditionExample
{
public static void main(String args[])
{
//creating two matrices
int a[][]={{1,3,4},{2,4,3},{3,4,5}};
int b[][]={{1,3,4},{2,4,3},{1,2,4}};

//creating another matrix to store the sum of two matrices


int c[][]=new int[3][3]; //3 rows and 3 columns
//adding and printing addition of 2 matrices
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=a[i][j]+b[i][j]; //use - for subtraction
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}
//java program for Multiplication of 2 Matrices
class MatrixMultiplicationExample{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};

//creating another matrix to store the multiplication of two matrices


int c[][]=new int[3][3]; //3 rows and 3 columns

//multiplying and printing multiplication of 2 matrices


for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}//end of k loop
System.out.print(c[i][j]+" "); //printing matrix element
}//end of j loop
System.out.println();//new line
}
}}
Example programs
// find the maximum and minimum values in a Java array
public class FindMaxMinUsingLoop
{
public static void main(String[] args)
{
int[] array = {5, 12, 9, 18, 3, 21};
int max = array[0]; // Assume the first element is the maximum initially
int min = array[0]; // Assume the first element is the minimum initially
for (int i = 1; i < array.length; i++)
{
if (array[i] > max)
{
max = array[i]; // Update maximum value
}
if (array[i] < min)
{
min = array[i]; // Update minimum value
}
}
System.out.println("Maximum value: " + max);
System.out.println("Minimum value: " + min);
}
}

//Example program to insert an element in array


class InsertElement
{
public static void main(String args[])
{
int a[]={10,20,30,40,50};
int pos=3;
int element=100;
for(int i=a.length-1;i>pos-1;i--)
{
a[i]=a[i-1];
}
a[pos-1]=element;
for(i=0;i<a.length;i++)
{
System.out.println(a[i]+” “);
}
}
}
//Example program for deleting a element in array
class DeleteElement
{
public static void main(String[]args)
{
int a={10,40,30,80,60,20};
int del_ele=30;
int count=0;
for(i=0;i<a.length;i++)
{
if(del_ele==a[i])
{
for(int j=i;j<a.length-1;j++)
{
a[j]=a[j+1];
}
count=count+1;
break;
}
}
if(count==0)
{
System.out.println(“Element not fount”);
}
else
{
System.out.println(“Element deleted successfully”);
for(i=0;i<a.length-1;i++)
{
System.out.println(a[i]+” “);
}
}
}
}
//Program to print the duplicate elements of an array

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]);
}
}
}
}

//Java Program to determine whether a given matrix is a sparse matrix

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.

public class SparseMatrix


{
public static void main(String[] args) {
int rows, cols, size, count = 0;

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

//Calculates the size of array


size = rows * cols;

//Count all zero element present in matrix


for(int i = 0; i < rows; i++){
for(int j = 0; j < cols; j++){
if(a[i][j] == 0)
count++;
}
}

if(count > (size/2))


System.out.println("Given matrix is a sparse matrix");
else
System.out.println("Given matrix is not a sparse matrix");
}
}

// Java Program to transpose matrix


public class MatrixTransposeExample{
public static void main(String args[]){
//creating a matrix
int original[][]={{1,3,4},{2,4,3},{3,4,5}};

//creating another matrix to store transpose of a matrix


int transpose[][]=new int[3][3]; //3 rows and 3 columns

//Code to transpose a matrix


for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
transpose[i][j]=original[j][i];
}
}
System.out.println("Printing Matrix without transpose:");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(original[i][j]+" ");
}
System.out.println();//new line
}
System.out.println("Printing Matrix After Transpose:");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(transpose[i][j]+" ");
}
System.out.println();//new line
}
}}

Passing Array to a Method


//Java Program to demonstrate the way of passing an array to method
class Testarray2
{
//creating a method which receives an array as a parameter
static void min(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}
}
Dynamic change of array size

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

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

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
{

// Main driver method


public static void main(String[] args)
{

// Get the Array


int intArr[] = { 10, 20, 15, 22, 35 };

Arrays.sort(intArr);

int intKey = 22;

// Print the key and corresponding index


System.out.println( intKey + " found at index = "+ Arrays.binarySearch(intArr, intKey));
}
}
// Java program to demonstrate Arrays.copyOf() method
import java.util.Arrays;

public class Main


{
public static void main(String[] args)
{

// Get the Array


int intArr[] = { 10, 20, 15, 22, 35 };

// To print the elements in one line


System.out.println("Integer Array: "+ Arrays.toString(intArr));

System.out.println("\nNew Arrays by copyOf:\n");

System.out.println("Integer Array: "+ Arrays.toString(Arrays.copyOf(intArr, 10)));


}
}
// Java program to demonstrate Arrays.copyOfRange() method

import java.util.Arrays;

public class Main


{
public static void main(String[] args)
{
// Get the Array
int intArr[] = { 10, 20, 15, 22, 35 };

// To print the elements in one line


System.out.println("Integer Array: "+ Arrays.toString(intArr));

System.out.println("\nNew Arrays by copyOfRange:\n");

// To copy the array into an array of new length


System.out.println("Integer Array: " + Arrays.toString(Arrays.copyOfRange(intArr, 1, 3)));
}
}

// Java program to demonstrate Arrays.equals() method


import java.util.Arrays;

public class Main


{
public static void main(String[] args)
{

// Get the Arrays


int intArr[] = { 10, 20, 15, 22, 35 };

// Get the second Arrays


int intArr1[] = { 10, 15, 22 };

// To compare both arrays


System.out.println("Integer Arrays on comparison: "+ Arrays.equals(intArr, intArr1));
}
}
// Java program to demonstrate Arrays.fill() method
import java.util.Arrays;

public class Main


{
public static void main(String[] args)
{

// Get the Arrays


int intArr[] = { 10, 20, 15, 22, 35 };

int intKey = 22;


Arrays.fill(intArr, intKey);

// To fill the arrays


System.out.println("Integer Array on filling: "+ Arrays.toString(intArr));
}
}
// Java program to demonstrate Arrays.sort() method

import java.util.Arrays;

public class Main


{
public static void main(String[] args)
{

// Get the Array


int intArr[] = { 10, 20, 15, 22, 35 };

// To sort the array using normal sort-


Arrays.sort(intArr);

System.out.println("Integer Array: " + Arrays.toString(intArr));


}
}

// Java program to demonstrate sort(originalArray, fromIndex,


endIndex) method

import java.util.Arrays;

public class Main


{
public static void main(String[] args)
{

// Get the Array


int intArr[] = { 10, 20, 15, 22, 35 };

// To sort the array using normal sort


Arrays.sort(intArr, 1, 3);

System.out.println("Integer Array: "+ Arrays.toString(intArr));


}
}
Java Vector
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store
n-number of elements in it as there is no size limit.
It is a part of Java Collection framework since Java 1.2. It is found in the java.util package
and implements the List interface, so we can use all the methods of List interface here.

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");

System.out.println("Elements are: "+vec);


}
}

//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));
}
}

You might also like