Java Arrays
Java Arrays
Normally, an array is a collection of similar type of elements which have a 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.
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.
Let us see the example of print the elements of Java array using the for-each loop.
//Java Program to print the array elements using for-each loop
class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}
Output:
33
3
4
5
System.out.println(min);
}
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.
//Java Program to demonstrate the case of
//ArrayIndexOutOfBoundsException in a Java Array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
}}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at TestArrayException.main(TestArrayException.java:5)
50
60
70
80
}}
Output:
I
}}
Output:
Printing original array:
33
3
4
5
Printing clone of the array:
33
3
4
5
Are both equal?
false