Array in Java
Array in Java
Array in Java
Normally, array is a collection of similar type of elements that have contiguous memory location.
In java, array is an object the contains elements of similar data type. It is a data structure where
we store similar elements. We can store only fixed elements in an array.
Advantage of Array
Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
Random access: We can get any data located at any index position.
Disadvantage of Array
Size Limit: We can store only 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.
Types of Array
Multidimensional Array
3. dataType arrayRefVar[];
1. arrayRefVar=new datatype[size];
Let's see the simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.
1. class B{
3.
5. a[0]=10;//initialization
6. a[1]=20;
7. a[2]=70;
8. a[3]=40;
9. a[4]=50;
10.
13. System.out.println(a[i]);
14.
15. }}
Output: 10
20
70
40
50
We can declare, instantiate and initialize the java array together by:
1. class B{
3.
5.
6. //printing array
8. System.out.println(a[i]);
9.
10. }}
Output:33
3
4
5
We can pass the array in the method so that we can reuse the same logic on any array.
Let's see the simple example to get minimum number of an array using method.
1. class B{
3. int min=arr[0];
4. for(int i=1;i<arr.length;i++)
5. if(min>arr[i])
6. min=arr[i];
7.
8. System.out.println(min);
9. }
10.
12.
15.
16. }}
Output:3
Multidimensional array
In such case, data is stored in row and column based index (also known as matrix form).
1. arr[0][0]=1;
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;
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
1. class B{
3.
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6.
7. //printing 2D array
8. for(int i=0;i<3;i++){
9. for(int j=0;j<3;j++){
11. }
12. System.out.println();
13. }
14.
15. }}
Output:1 2 3
2 4 5
4 4 5
In java, array is an object. For array object, an proxy class is created whose name can be
obtained by getClass().getName() method on the object.
1. class B{
3.
4. int arr[]={4,4,5};
5.
6. Class c=arr.getClass();
7. String name=c.getName();
8.
9. System.out.println(name);
10.
11. }}
Output:I
Copying an array
3. )
1. class ArrayCopyDemo {
6.
8. System.out.println(new String(copyTo));
9. }
10. }
Output:caffein
Addition 2 matrices
1. class AE{
4. int a[][]={{1,3,4},{3,4,5}};
5. int b[][]={{1,3,4},{3,4,5}};
6.
9.
13. c[i][j]=a[i][j]+b[i][j];
15. }
17. }
18.
19. }}
Output:2 6 8
6 8 10