- An array is a collection of similar data type of elements which has contiguous memory location.
- Java array is an object which contains elements of a similar data type. Additionally, 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.
- We can get the length of the array using the length member.
- In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and implements the serializable as well as cloneable interfaces. We can store primitive values or objects in an array
- In Java, we can also create single dimensional or multi dimensional arrays in Java.
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.
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 Array in java: There are two types of array.
1. Single Dimensional Array
2. Two Dimensional Array
3. Multidimensional Array
1.Single Dimensional Array
Syntax:
dataType[] arr; (or) dataType []arr; (or) dataType arr[];
3. Multidimensional Array
1.Single Dimensional Array
Syntax:
dataType[] arr; (or) dataType []arr; (or) dataType arr[];
int[] a; (or) int []a; (or) int a[];
Instantiation of an Array in Java
arrayRefVar = new datatype[size];
Ex: a = new int[5];
Declare : int[] a;
Creation or Instantiation : a = new int[5];
Creation or Instantiation : a = new int[5];
Declare & Creation or Instantiation : : int[] a = new int[5];
Initialization of array :providing initial value
Ex 1: Program to declare, instantiate, initialize and traverse Array.
Ex 1: Program to declare, instantiate, initialize and traverse Array.
class Testarray
{
public static void main(String args[])
{
int a[]; // declaration
a=new int[5]; // instantiation
//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<a.length;i++) //length is the property of array
System.out.println(a[i]);
}
}
Output:
I:\>javac Testarray.java
I:\>java Testarray
10
20
70
40
50
10
20
70
40
50
Ex 2: Declaration, Instantiation and Initialization
class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);
}
}
Output:
I:\>java Testarray1
33
3
4
5
33
3
4
5
Ex 3:
Sum = 36
Average = 3.6
class Testarray
{
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);
}
}
Output:Sum = 36
Average = 3.6
For-each Loop for Java Array
We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then executes the body of the loop.
Syntax: for(initialization;condition;increment/decrement)
{
{
//body of the loop
}
for(data_type variable:array)
{
//body of the loop
}
//body of the loop
}
for(int i:arr)
{
{
//code
}
Passing Array to a Method
Ex:
3
Ex:
class Testarray
{
//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
}
}
Output:3
Anonymous Array
10
22
44
66
An array in Java without any name is known as anonymous array. It is an array just for creating and using instantly. We can create an array without name, such type of nameless arrays are called anonymous arrays. The main purpose of anonymous array is just for instant use.
Ex:public class TestAnonymousArray
{
//creating a method which receives an array as a parameter
static void printArray(int arr[])
{
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
public static void main(String args[])
{
printArray(new int[]{10,22,44,66}); //passing anonymous array to method
}
}
Output:10
22
44
66
Returning Array from the Method
Ex:
10
30
50
90
60
Ex:
class TestReturnArray
{
//creating method which returns an array
static int[] get()
{
return new int[]{10,30,50,90,60};
}
public static void main(String args[])
{
//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
}
Output:10
30
50
90
60
Array Index Out Of Bounds Exception
The Java Virtual Machine (JVM) throws an Array Index Out Of Bounds Exception if length of the array is negative, equal to the array size or greater than the array size while traversing the array.
Ex:
//Java Program to demonstrate the case of ArrayIndexOutOfBoundsException in a Java Array.
public class TestArrayException
{
public static void main(String args[])
{
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++)
{
System.out.println(arr[i]);
}
}
}
Output:
I:\>javac TestArrayException.java I:\>java TestArrayException
50
60
70
80
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at TestArrayException.main(TestArrayException.java:5)
2.Two Dimensional Array: Identify the following Arrays and mention the type of arrays
50
60
70
80
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at TestArrayException.main(TestArrayException.java:5)
2.Two Dimensional Array: Identify the following Arrays and mention the type of arrays
1)
int [][]a; // 2D
2)
int[] []a; // 2D
int a[][]; // 2D
int[] a[]; // 2D
3)
int[] a,b; //a->1D b->1D
int a[],b; //a->1D b->NOT AN ARRAY
4)
int[][] a,b; //a->2D b->2D
int[] a[],b; //a->2D b->1D
int[] a[],b[]; //a->2D b->2D
int[][] a[],b[]; //a->3D b->3D
int[][] a,[]b; //a->2D b->Compile Time Error
Declare : int[][] a;
Creation : a = new int[2][3];
int [][]a; // 2D
2)
int[] []a; // 2D
int a[][]; // 2D
int[] a[]; // 2D
3)
int[] a,b; //a->1D b->1D
int a[],b; //a->1D b->NOT AN ARRAY
4)
int[][] a,b; //a->2D b->2D
int[] a[],b; //a->2D b->1D
int[] a[],b[]; //a->2D b->2D
int[][] a[],b[]; //a->3D b->3D
int[][] a,[]b; //a->2D b->Compile Time Error
Declare : int[][] a;
Creation : a = new int[2][3];
Example: Matrix Multiplication
import java.util.Scanner;
public class MatrixMultiplicationExample
{
public static void main(String args[])
{
int row1, col1, row2, col2;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of rows in first matrix:");
row1 = s.nextInt();
System.out.print("Enter number of columns in first matrix:");
col1 = s.nextInt();
System.out.print("Enter number of rows in second matrix:");
row2 = s.nextInt();
System.out.print("Enter number of columns in second matrix:");
col2 = s.nextInt();
if (col1 != row2)
{
System.out.println("Matrix multiplication is not possible");
}
else
{
int a[][] = new int[row1][col1];
int b[][] = new int[row2][col2];
int c[][] = new int[row1][col2];
System.out.println("Enter values for matrix A : \n");
for (int i = 0; i < row1; i++)
{
for (int j = 0; j < col1; j++)
a[i][j] = s.nextInt();
}
System.out.println("Entered values in matrix A : \n");
for (int i = 0; i < row1; i++)
{
for (int j = 0; j < col1; j++)
{
System.out.print(a[i][j]+ " ");
}
System.out.println( );
}
System.out.println("Enter values for matrix B : \n");
for (int i = 0; i < row2; i++)
{
for (int j = 0; j < col2; j++)
b[i][j] = s.nextInt();
}
System.out.println("Entered values in matrix B : \n");
for (int i = 0; i < row2; i++)
{
for (int j = 0; j < col2; j++)
{
System.out.print(b[i][j]+ " ");
}
System.out.println( );
}
System.out.println("Matrix multiplication is : \n");
for(int i = 0; i < row1; i++)
{
for(int j = 0; j < col2; j++)
{
c[i][j]=0;
for(int k = 0; k < col1; k++)
{
c[i][j] += a[i][k] * b[k][j];
}
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}
}
public class MatrixMultiplicationExample
{
public static void main(String args[])
{
int row1, col1, row2, col2;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of rows in first matrix:");
row1 = s.nextInt();
System.out.print("Enter number of columns in first matrix:");
col1 = s.nextInt();
System.out.print("Enter number of rows in second matrix:");
row2 = s.nextInt();
System.out.print("Enter number of columns in second matrix:");
col2 = s.nextInt();
if (col1 != row2)
{
System.out.println("Matrix multiplication is not possible");
}
else
{
int a[][] = new int[row1][col1];
int b[][] = new int[row2][col2];
int c[][] = new int[row1][col2];
System.out.println("Enter values for matrix A : \n");
for (int i = 0; i < row1; i++)
{
for (int j = 0; j < col1; j++)
a[i][j] = s.nextInt();
}
System.out.println("Entered values in matrix A : \n");
for (int i = 0; i < row1; i++)
{
for (int j = 0; j < col1; j++)
{
System.out.print(a[i][j]+ " ");
}
System.out.println( );
}
System.out.println("Enter values for matrix B : \n");
for (int i = 0; i < row2; i++)
{
for (int j = 0; j < col2; j++)
b[i][j] = s.nextInt();
}
System.out.println("Entered values in matrix B : \n");
for (int i = 0; i < row2; i++)
{
for (int j = 0; j < col2; j++)
{
System.out.print(b[i][j]+ " ");
}
System.out.println( );
}
System.out.println("Matrix multiplication is : \n");
for(int i = 0; i < row1; i++)
{
for(int j = 0; j < col2; j++)
{
c[i][j]=0;
for(int k = 0; k < col1; k++)
{
c[i][j] += a[i][k] * b[k][j];
}
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}
}
Output:
C:\Users\Student\Desktop\java prg>javac MatrixMultiplicationExample.java
C:\Users\Student\Desktop\java prg>java MatrixMultiplicationExample
Enter number of rows in first matrix:2
Enter number of columns in first matrix:2
Enter number of rows in second matrix:2
Enter number of columns in second matrix:2
Enter values for matrix A :
11
22
33
44
Entered values in matrix A :
11 22
33 44
Enter values for matrix B :
1
2
3
4
Entered values in matrix B :
1 2
3 4
Matrix multiplication is :
77 110
165 242
Example :Matrix Addition
import java.util.Scanner;
public class MatrixAdditionExample
{
public static void main(String args[])
{
int row1, col1, row2, col2;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of rows in first matrix:");
row1 = s.nextInt();
System.out.print("Enter number of columns in first matrix:");
col1 = s.nextInt();
System.out.print("Enter number of rows in second matrix:");
row2 = s.nextInt();
System.out.print("Enter number of columns in second matrix:");
col2 = s.nextInt();
if (col1 != row2)
{
System.out.println("Matrix Addition is not possible");
}
else
{
int a[][] = new int[row1][col1];
int b[][] = new int[row2][col2];
int c[][] = new int[row1][col2];
System.out.println("Enter values for matrix A : \n");
for (int i = 0; i < row1; i++)
{
for (int j = 0; j < col1; j++)
a[i][j] = s.nextInt();
}
System.out.println("Entered values in matrix A : \n");
for (int i = 0; i < row1; i++)
{
for (int j = 0; j < col1; j++)
{
System.out.print(a[i][j]+ " ");
}
System.out.println( );
}
System.out.println("Enter values for matrix B : \n");
for (int i = 0; i < row2; i++)
{
for (int j = 0; j < col2; j++)
b[i][j] = s.nextInt();
}
System.out.println("Entered values in matrix B : \n");
for (int i = 0; i < row2; i++)
{
for (int j = 0; j < col2; j++)
{
System.out.print(b[i][j]+ " ");
}
System.out.println( );
}
for(int i = 0; i < row1; i++)
{
for(int j = 0; j < col2; j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
System.out.println("Matrix addition is : \n");
for(int i = 0; i < row1; i++)
{
for(int j = 0; j < col2; j++)
{
System.out.print(c[i][j]+ " ");
}
System.out.println();
}
}
}
}
public class MatrixAdditionExample
{
public static void main(String args[])
{
int row1, col1, row2, col2;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of rows in first matrix:");
row1 = s.nextInt();
System.out.print("Enter number of columns in first matrix:");
col1 = s.nextInt();
System.out.print("Enter number of rows in second matrix:");
row2 = s.nextInt();
System.out.print("Enter number of columns in second matrix:");
col2 = s.nextInt();
if (col1 != row2)
{
System.out.println("Matrix Addition is not possible");
}
else
{
int a[][] = new int[row1][col1];
int b[][] = new int[row2][col2];
int c[][] = new int[row1][col2];
System.out.println("Enter values for matrix A : \n");
for (int i = 0; i < row1; i++)
{
for (int j = 0; j < col1; j++)
a[i][j] = s.nextInt();
}
System.out.println("Entered values in matrix A : \n");
for (int i = 0; i < row1; i++)
{
for (int j = 0; j < col1; j++)
{
System.out.print(a[i][j]+ " ");
}
System.out.println( );
}
System.out.println("Enter values for matrix B : \n");
for (int i = 0; i < row2; i++)
{
for (int j = 0; j < col2; j++)
b[i][j] = s.nextInt();
}
System.out.println("Entered values in matrix B : \n");
for (int i = 0; i < row2; i++)
{
for (int j = 0; j < col2; j++)
{
System.out.print(b[i][j]+ " ");
}
System.out.println( );
}
for(int i = 0; i < row1; i++)
{
for(int j = 0; j < col2; j++)
{
c[i][j] = a[i][j] + b[i][j];
}
}
System.out.println("Matrix addition is : \n");
for(int i = 0; i < row1; i++)
{
for(int j = 0; j < col2; j++)
{
System.out.print(c[i][j]+ " ");
}
System.out.println();
}
}
}
}
Output:
C:\Users\Student\Desktop\java prg>javac MatrixAdditionExample.java
C:\Users\Student\Desktop\java prg>java MatrixAdditionExample
Enter number of rows in first matrix:2
Enter number of columns in first matrix:2
Enter number of rows in second matrix:2
Enter number of columns in second matrix:2
Enter values for matrix A :
11
22
33
44
Entered values in matrix A :
11 22
33 44
Enter values for matrix B :
1
2
3
4
Entered values in matrix B :
1 2
3 4
Matrix addition is :
12 24
36 48
3.Multi Dimensional Array
A multidimensional array is an array of arrays. That is, each element of a multidimensional array is an array itself.
A multidimensional array is an array of arrays. That is, each element of a multidimensional array is an array itself.
Syntax: Declaration
dataType[][][] arrayRefVar; (or)
dataType [][][]arrayRefVar; (or)
dataType arrayRefVar[][][]; (or)
Syntax: Instantiation
int[][][]<arrayName>=new int[no.of.rows][no.of.columns];
int[][][]<arrayName>=new int[no.of.rows][no.of.columns];
Ex:
int[][][] arr=new int[3][4][5]; //3 dimensions 4 row and 5 column
int[][][] arr=new int[3][4][5]; //3 dimensions 4 row and 5 column
Syntax: Initialization
<arrayName>[row_index][col_index]=value;
<arrayName>[row_index][col_index]=value;
Ex:
arr[0][0][0]=1;
arr[0][0][0]=1;
Ex:class ThreeDimensionalArray
{
public static void main(String[] args)
{
//initialize 3-d array
int[][][] a = { { { 10, 20}, { 30, 40, 50 , 60 } , { 70, 80, 90 } } };
System.out.println ("3-d array is given below :");
//print the elements of array
for (int i = 0; i < a.length; i++) // a.length = 1
{
for (int j = 0; j < a[i].length; j++) // a[i].length = 2
{
public static void main(String[] args)
{
//initialize 3-d array
int[][][] a = { { { 10, 20}, { 30, 40, 50 , 60 } , { 70, 80, 90 } } };
System.out.println ("3-d array is given below :");
//print the elements of array
for (int i = 0; i < a.length; i++) // a.length = 1
{
for (int j = 0; j < a[i].length; j++) // a[i].length = 2
{
for (int k = 0; k < a[i][j].length; k++)
{
System.out.println ("a [" + i + "][" + j + "][" + k + "] = " + a [i][j][k]);
for (int k = 0; k < a[i][j].length; k++)
{
System.out.println ("a [" + i + "][" + j + "][" + k + "] = " + a [i][j][k]);
//System.out.println(a[i][j][k]+" ");
}
System.out.println();
}
}
}
}
output:
System.out.println();
}
}
}
}
output:
ubuntu@ubuntu:~/Desktop/rkjava$ javac ThreeDimensionalArray.java
ubuntu@ubuntu:~/Desktop/rkjava$ java ThreeDimensionalArray
3-d array is given below :
a [0][0][0] = 10
a [0][0][1] = 20
a [0][1][0] = 30
a [0][1][1] = 40
a [0][1][2] = 50
a [0][1][3] = 60
a [0][2][0] = 70
a [0][2][1] = 80
a [0][2][2] = 90
ubuntu@ubuntu:~/Desktop/rkjava$ java ThreeDimensionalArray
3-d array is given below :
a [0][0][0] = 10
a [0][0][1] = 20
a [0][1][0] = 30
a [0][1][1] = 40
a [0][1][2] = 50
a [0][1][3] = 60
a [0][2][0] = 70
a [0][2][1] = 80
a [0][2][2] = 90
Output:
if we use this statement System.out.println(a[i][j][k]+" ");
ubuntu@ubuntu:~/Desktop/rkjava$ javac ThreeDimensionalArray.java
ubuntu@ubuntu:~/Desktop/rkjava$ java ThreeDimensionalArray
3-d array is given below :
10
20
30
40
50
60
70
80
90
ubuntu@ubuntu:~/Desktop/rkjava$ java ThreeDimensionalArray
3-d array is given below :
10
20
30
40
50
60
70
80
90
No comments:
Post a Comment