Unit-5 Array
Introduction of Array
An array is a collection of similar data types.Each
item of an array is an element. All the elements in
an array must be of the same type. Array is a
container object that holds values
of homogeneous type. It is also known as static
data structure because size of an array must be
specified at the time of its declaration.We can
store only a fixed set of elements in a Java array.
Array in Java is index-based soarray starts from zero index and goes to n-1 where n is length of the array.The
first element of the array is stored at the 0th index, and second element is stored on 1st index and so on.
In Java, array is treated as an object and stores into heap memory. An int array can contain int values,and
a String array can contain string values.Written after the variable name, the index number is enclosed in
brackets. So if the variable name is x, we could access a specific element with an expression like x[5].
Declaring an array
Before you can create an array, you must declare a variable that refers to the array. This variable declaration
should indicate the type of elements stored by the array, followed by a set of empty brackets, like this:
String[] names;
Here, a variable named names is declared. Its type is an array of String objects.
You can also put the brackets on the variable name rather than the type. The following two statements both
create arrays of int elements:
int[] array1; // an array of int elements
int array2[]; // another array of int elements
Declaring an array doesn’t actually create the array. To do that, you must use the new keyword, followed by
the array type. For example:
String[] names;
names = new String[10];
Or
String[] names = new String[10];
Initializing array elements
You can initialize an array by assigning values one by one, like this:
String[] Days = new String[7];
Days[0] = "Sunday";
Days[1] = "Monday";
Days[2] = "Tuesday";
Days[3] = "Wednesday";
Days[4] = "Thursday";
Days[5] = "Friday";
Days[6] = "Saturday";
Or you can use the following shorthand:
String[] days = { "Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday",
1
"Friday", "Saturday" };
Here, each element to be assigned to the array is listed in an array initializer. The number of values listed in
the initializer determines the length of the array that the initializer creates.
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.
Types of Arrays
There are two types of array.
Single Dimensional Array.
Multidimensional Array.
Single dimensional array
A single dimensional array is a normal array where the array contains sequential elements (of same type).
Single dimensional array use single index to store elements. You can get all the elements of array by just
increment its index by one.
Array Declaration
Syntax :
Datatype[] arrayName;
Or
DatatypearrayName[];
Java allows declaring array by using both declaration syntax, both are valid.
The arrayName can be any valid array name and datatype can be any like: int, float, byte etc.
Example :
int[] a;
Initialization of Array
Initialization is a process of allocating memory to an array. At the time of initialization, we specify the size of
array to reserve memory area.
Initialization Syntax:
arrayName=new datatype[size];
The arrayName is the name of array, new is a keyword used to allocate memory and size is length of array.
We can combine both declaration and initialization in a single statement.
Datatype[]arrayName=new datatype[size];
Accessing array element
We can access array elements by its index value either by using loop or direct index value. We can use loop
like: for, for-each or while to traverse the array elements.
Example to access elements
Class Demo{
public static void main (String[] args)
{
int[] arr={10,20,30,40,50};
for(inti=0; i<arr.length;i++)
{
System.out.println(arr[i]);
}
System.out.println(“element at first index: ”+ arr[1]);
2
}
}
Example
publicclassTestArray{
publicstaticvoid main(String[]args){
double[]myList={1.9,2.9,3.4,3.5};
// Print all the array elements
for(inti=0;i<myList.length;i++){
System.out.println(myList[i]+" ");
}
// Summing all elements
double total =0;
for(inti=0;i<myList.length;i++){
total+=myList[i]; // total=total+myList[i]
}
System.out.println("Total is "+ total);
// Finding the largest element
double max =myList[0];
for(inti=1;i<myList.length;i++){
if(myList[i]> max)
max=myList[i];
}
System.out.println("Max is "+ max);
}
}
Output
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
Multi-dimensional array
A multi-dimensional array in Java is an array of arrays. It can have multiple rows and multiple columns unlike
single dimensional array, which can have only one row index.A two dimensional array is an array of one
dimensional arrays and a three dimensional array is an array of two dimensional arrays.It represents data into
tabular form in which data is stored into rows and columns.
Multi-Dimensional Array Declaration
datatype[ ][ ] arrayName;
Initialization of Array
datatype[ ][ ] arrayName = new datatype[no_of_rows][no_of_columns];
3
The arrayName is the name of array, new is a keyword used to allocate memory and no_of_rows and
no_of_columns both are used to set size of rows and columns elements. Like single dimensional array, we can
statically initialize multi-dimensional array as well.
int[ ][ ] arr = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
Example:
class Demo
{
public static void main(String[] args)
{
intarr[ ][ ] = {{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15}};
for(inti=0;i<3;i++)
{
for (int j = 0; j < 5; j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
// assigning a value
System.out.println("element at first row and second column: " +arr[0][1]);
}
}
Example
publicclassTester{
publicstaticvoid main(String[]args){
int[][]multidimensionalArray={{1,2},{2,3},{3,4}};
for(inti=0;i<3;i++){
//row
for(int j =0; j <2; j++){
System.out.print(multidimensionalArray[i][j]+" ");
}
System.out.println();
}
}
}
Output
12
23
34
Processing Arrays
When processing array elements, we often use either for loop or foreach loop because all of the elements in
an array are of the same type and the size of the array is known.
Example
Here is a complete example showing how to create, initialize, and process arrays −
publicclassTestArray{
4
publicstaticvoid main(String[]args){
double[]myList={1.9,2.9,3.4,3.5};
// Print all the array elements
for(inti=0;i<myList.length;i++){
System.out.println(myList[i]+" ");
}
// Summing all elements
double total =0;
for(inti=0;i<myList.length;i++){
total+=myList[i];
}
System.out.println("Total is "+ total);
// Finding the largest element
double max =myList[0];
for(inti=1;i<myList.length;i++)
{
if(myList[i]> max)
max=myList[i];
}
System.out.println("Max is "+ max);
}
}
For-each Loop for Java Array
The Java for-each loop prints the array elements one by one. It holds an array element in a variable, than
executes the body of the loop.
The syntax of for-each loop is given below:
for(data_type variable:array){
//body of the loop
}
Example:-Java Program to print the array elements using for-each loop
class Testarray1{
public static void main(String args[]){
int[] arr={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}
Output:
33
5
3
4
5
Passing Array to a Method in Java
We can pass the java array to method so that we can reuse the same logic on any array.
Let's see the simple example to get the minimum number of an array using 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 mn(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
mn(a);//passing array to method
}}
Returning Array from the Method
We can also return an array from the method in Java.
//Java Program to return an array from the method
class TestReturnArray{
//creating method which returns an array
static int get(){
int[] a=new int[]{10,20,30,40,50};
return a[];
}
public static void main(String args[]){
//calling method which returns an array
int arr[]=get(a[]);
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}}
The Arrays Class
6
The Arrays class in java.util package is a part of the Java Collection Framework. The java.util.Arrays 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. The
java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and
filling array elements. These methods are overloaded for all primitive types.
Sr.No Method & Description
.
1
public static int binarySearch(Object[] a, Object key)
Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using the binary
search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if
it is contained in the list; otherwise, it returns ( – (insertion point + 1)).
2
public static boolean equals(long[] a, long[] a2)
Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal
if both arrays contain the same number of elements, and all corresponding pairs of elements in the two
arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other
primitive data types (Byte, short, Int, etc.)
3
public static void fill(int[] a, intval)
Assigns the specified int value to each element of the specified array of ints. The same method could be
used by all other primitive data types (Byte, short, Int, etc.)
4
public static void sort(Object[] a)
Sorts the specified array of objects into an ascending order, according to the natural ordering of its
elements. The same method could be used by all other primitive data types ( Byte, short, Int, etc.)
The java.util.Arrays.binarySearch(double[ ] a, double key) method searches the specified array of doubles
for the specified value using the binary search algorithm. The array must be sorted prior to making this call.
This returns index of the search key, if it is contained in the list; otherwise, it returns ( – (insertion point + 1)).
Declaration
Following is the declaration for java.util.Arrays.binarySearch() method
public static int binarySearch(double[] a, double key)
Parameters
a − This is the array to be searched.
key − This is the value to be searched for.
Return Value
This method returns index of the search key, if it is contained in the array, else it returns (-(insertion point+
1)). The insertion point is the point at which the key would be inserted into the array: the index of the first
element greater than the key, or a.length if all elements in the array are less than the specified key.
7
Example
The following example shows the usage of java.util.Arrays.binarySearch() method and
java.util.Arrays.sort() method
package binarysc;
import java.util.Arrays;
public class BinarySc {
public static void main(String[] args) {
// initializing unsorted int array
int a[]=new int[]{4,7,3,8,1};
System.out.println("Unsorted Array");
for(int number :a)
{
System.out.print(number+" ");
}
Arrays.sort(a);
// let us print all the elements available in list
System.out.println("\nThe sorted array is:");
for(int number :a)
{
System.out.print(number+" ");
}
// entering the value to be searched
searchVal=8;
retVal=Arrays.binarySearch(a,searchVal);
System.out.println("\nThe index of element 8 is : "+retVal);
}
}
Output
Unsorted Array
47381
The sorted array is:
13478
The index of element 8 is: 1
Example: The following example shows the usage of java.util.Arrays.equals() method
package comparematrix;
import java.util.Arrays;
public class Comparematrix {
public static void main(String[] args) {
int a[]={4,7,3,8,1};
int b[]={4,7,3,8,1};
boolean n=Arrays.equals(a, b);
System.out.println(n);
}
}
Output: true
Example: The following example shows the usage of java.util.Arrays.fill() method
package fillarray;
8
import java.util.Arrays;
public class Fillarray {
public static void main(String[] args) {
int a[]={4,7,3,8,1};
int val=5;
Arrays.fill(a,val);
for(int number:a)
{
System.out.print(number+" ");
}
}
}
Output: 5 5 5 5 5
Programs
1. Addition of 2 Matrices in Java
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}}
2. Java Program to print Odd and Even Numbers from an Array
public 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]);
9
}
}
}}
3. Multiplication of 2 Matrices in Java
In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all the
columns of the second matrix which can be understood by the image given below.
Let's see a simple example to multiply two matrices of 3 rows and 3 columns.
//Java Program to multiply two matrices
public 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
10
}//end of j loop
System.out.println();//new line
}
}}
4. Program to copy all elements of one array into another array
In this program, we need to copy all the elements of one array into another. This can be accomplished
by looping through the first array and store the elements of the first array into the second array at the
corresponding position.
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[arr1.length];
//Copying all elements of one array into another
for (int i = 0; i < arr1.length; i++) {
arr2[i] = arr1[i];
}
//Displaying elements of array arr1
System.out.println("Elements of original array: ");
for (int i = 0; i < arr1.length; i++) {
System.out.print(arr1[i] + " ");
}
System.out.println();
//Displaying elements of array arr2
System.out.println("Elements of new array: ");
for (int i = 0; i < arr2.length; i++) {
System.out.print(arr2[i] + " ");
}
}
}
5. Program to print the largest element in an array
public class LargestElement_array {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {25, 11, 7, 75, 56};
//Initialize max with first element of array.
int max = arr[0];
//Loop through the array
for (int i = 1; i < arr.length; i++) {
//Compare elements of array with max
if(arr[i] > max)
max = arr[i];
}
System.out.println("Largest element present in given array: " + max);
}
11
}
6. Program to print the smallest element in an array
public class SmallestElement_array {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {25, 11, 7, 75, 56};
//Initialize min with first element of array.
int min = arr[0];
//Loop through the array
for (int i = 1; i < arr.length; i++) {
//Compare elements of array with min
if(arr[i] <min)
min = arr[i];
}
System.out.println("Smallest element present in given array: " + min);
}
}
7. Program to print the elements of an array in reverse order
public 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] + " ");
}
}
}
8. Java Program to print the sum of all the items of the array
public class SumOfArray {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
int sum = 0;
//Loop through the array to calculate sum of elements
for (int i = 0; i < arr.length; i++) {
12
sum = sum + arr[i];
}
System.out.println("Sum of all the elements of an array: " + sum);
}
}
9. Java Program to find Third Largest Number in an Array
public class ThirdLargestInArrayExample{
public static int getThirdLargest(int[] a, int total){
int temp;
for (int i = 0; i < total; i++)
{
for (int j = i + 1; j < total; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return a[total-3];
}
public static void main(String args[]){
int a[]={1,2,5,6,3,2};
int b[]={44,66,99,77,33,22,55};
System.out.println("Third Largest: "+getThirdLargest(a,6));
System.out.println("Third Largest: "+getThirdLargest(b,7));
}}
10. Java Program to transpose matrix
Converting rows of a matrix into columns and columns of a matrix into row is called transpose of a 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]+" ");
13
}
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
}
}}
14