Experiment 5
Experiment 5
: 05
Theory:
Java Arrays
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.
Arrays in Java are index-based, the first element of the array is stored at the 0th index,
2nd element is stored on the 1st index and so on.
In Java, an 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
dimensional or multidimensional arrays in Java.
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, a collection framework is used in Java
which grows automatically.
Program 1: Java Program to illustrate how to declare, instantiate, initialize and traverse the Java
array.
//Java Program to illustrate how to declare, instantiate, initialize and traverse the
Java array.
class Testarray1 {
public static void main(String args[]) {
int a[] = new int[5]; //declaration and instantiation
a[0]=10; //initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);
}
}
Output
10
20
70
40
50
We can declare, instantiate and initialize the java array together by:
class Testarray2{
public static void main(String args[]) {
int a[]={33,3,4,5}; //declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
}
}
Output
33
3
4
5
In such case, data is stored in row and column based index (also known as matrix
form).
class Testarray3{
public static void main(String args[]) {
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
Output
123
245
445
Conclusion: In this way, we have studied how to use array for storing various types
of elements in java