5.1 Java Arrays12
5.1 Java Arrays12
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.
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: 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.
o Multidimensional Array
1) Single Dimensional Array in Java
An array that represent in a single dimensional is called single dimensional array
14. }}
Test it Now
Output:
10
20
70
40
50
1.
.
2) Multidimensional Array in Java
An array that represent in two dimension i.e. row and column based index is called matrix.
Syntax to Declare Multidimensional Array in Java
2. arr[0][1]=2;
3. arr[0][2]=3;
4. arr[1][0]=4;
5. arr[1][1]=5;
6. arr[1][2]=6;
7. arr[2][0]=7;
8. arr[2][1]=8;
9. arr[2][2]=9;
8. for( j=0;j<3;j++){
9. System.out.print(arr[i][j]+" ");
10. }
11. System.out.println();
12. }
13. }}
Test it Now
Output:
1 2 3
2 4 5
4 4 5
Output:
2 6 8
6 8 10
Let's see a simple example to multiply two matrices of 3 rows and 3 columns.
1. //Java Program to multiply two matrices
Output:
6 6 6
12 12 12
18 18 18
Related Topics
1) Java Program to copy all elements of one array into another array
12) Java Program to print the sum of all the items of the array
25) Java Program to find the frequency of odd & even numbers in the given
matrix
27) Java Program to find the sum of each row and each column of a matrix