unit_5_array_in_java
unit_5_array_in_java
An array is typically a grouping of elements of the same kind that are stored in a single,
contiguous block of memory.
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.
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: Arrays have a fixed size and do not grow dynamically at runtime.
A single-dimensional array in Java is a linear collection of elements of the same data type. It
is declared and instantiated using the following syntax:
simple example of java array, where we are going to declare, instantiate, initialize and
traverse an array.
Example
Example
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
public class Main{
public static void main(String args[]){
int a[]={33,3,4,5};
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);
}
}
Compile and Run
Output:
33
3
4
5
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.
Example
System.out.println("Sorted Array:");
for ( i = 0; i < 10; i++) {
System.out.print(a[i] + " ");
}
}
}
A multidimensional array in Java is an array of arrays where each element can be an array
itself. It is useful for storing data in row and column format.
1. dataType 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 of Multidimensional Java Array
simple example to declare, instantiate, initialize and print the 2Dimensional array.
Example
MatrixMultiplicationExample.java
//Write a program to assign two matrix elements and calculate matrix multiplication.
public class Matrixmult{
public static void main(String args[])
{
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
// matric addition
for ( i = 0; i < 2; i++) {
for(j=0;j<2;j++)
{
c[i][j] = a[i][j]+b[i][j];
}}
System.out.println("Addition of matrix:");
for ( i = 0; i < 2; i++) {
for(j=0;j<2;j++)
{
System.out.println(c[i][j]+"");
}}}}
WAP to enter 3x3 two matrixes and calculate matrix multiplication using scanner class.
package matrixaddition;
import java.util.Scanner;
a[i][j] = sc.nextInt();
}}