Arrays
Arrays
INTRODUCTION
• An Array is a collection of similar 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.
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 ARRAY
• class ExampleForEachLoop {
• public static void main(String args[]) {
• int arr[]={1,2,4,5};
• //printing array using for-each loop
• for(int i:arr)
• System.out.println(i);
• }}
OUTPUT
•1
•2
•4
•5
MULTIDIMENSIONAL ARRAY
• dataType[][] arrayRefVar;
• dataType [][]arrayRefVar;
• dataType arrayRefVar[][];
• dataType []arrayRefVar[];
EXAMPLE OF MULTIDIMENSIONAL ARRAY
• class ExampleArray2 {
• public static void main(String args[]) {
• int ar[][]={{1,2,3},{2,4,5},{4,5,6}};
• for(int i=0;i<3;i++){
• for(int j=0;j<3;j++){
• System.out.print(ar[i][j]+" ");
• }
• System.out.println();
• }
• }}
OUTPUT
•1 2 3
•2 4 5
•4 5 6
ADDITION OF TWO MATRICES
• class MatrixAddition {
• public static void main(String args[]) {
• int a[][]={{1,3,4},{3,4,5}};
• int b[][]={{1,3,4},{3,4,5}};
• int c[][]=new int[2][3];
• 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
•} } }
OUTPUT
•2 6 8
• 6 8 10
MULTIPLICATION OF TWO MATRICES
• public class MatrixMultiplication {
• 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}};
• int c[][]=new int[3][3];
• 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]; }
• System.out.print(c[i][j]+" "); }
System.out.println();
• } }}
OUTPUT
•6 6 6
• 12 12 12
• 18 18 18