Array Notes
Array Notes
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.
Unlike C/C++, we can get the length of the array using the length member. In C/C+
+, we need to use the sizeof operator.
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. Like C/C++, we can also create
single dimentional or multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in
C/C++.
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.
Types of Array in java
There are two types of array.
1. arrayRefVar=new datatype[size];
Output:
10
20
70
40
50
Output:
33
3
4
5
1. for(data_type variable:array){
2. //body of the loop
3. }
Let us see the example of print the elements of Java array using the for-each loop.
Output:
33
3
4
5
Let's see the simple example to get the minimum number of an array using a
method.
Output:
Output:
10
22
44
66
Output:
10
30
50
90
60
ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length
of the array in negative, equal to the array size or greater than the array size while
traversing the array.
Output:
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;
Output:
1 2 3
2 4 5
4 4 5
Output:
0 1 2
3 4 5 6
7 8
Output:
Output:
caffein
Cloning an Array in Java
Since, Java array implements the Cloneable interface, we can create the clone of the
Java array. If we create the clone of a single-dimensional array, it creates the deep
copy of the Java array. It means, it will copy the actual value. But, if we create the
clone of a multidimensional array, it creates the shallow copy of the Java array which
means it copies the references.
Output:
Output:
2 6 8
6 8 10
Output:
6 6 6
12 12 12
18 18 18
Related Topics
12) Java Program to print the sum of all the items of the array
32) Java Program to find the frequency of odd & even numbers
in the given matrix
33) Java Program to find the product of two matrices
34) Java Program to find the sum of each row and each column
of a matrix