2. Array
2. Array
Advantages
Code Optimization: It makes the code optimized, we can retrieve or
sort the data efficiently.
Random access: We can get any data located at an index
position.
1
Disadvantages
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
Single Dimensional Array
Multi-Dimensional Array
Creating Arrays
You can create an array by using the new operator with the following
syntax −
2
Syntax
myList=new myList[size];
The above statement does two
things −
• It creates an array using new Operator
• It assigns the reference of the newly created array to the variable
myList.
Example
int[] myArray = new int[10];
Array myArray is created with size 10 and the value is accessed by it’s index
which starts from 0 to n-1.
0 1 2 3 4 5 6 7
8 9
11 71 13 20 74 54 89 12 25 36
Processing Arrays
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5]; //declaration and
instantiation
a[0]=10;
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
3
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
int total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
}
Example
public class TestArray {
4
}
}
}
}
}
class TestReturnArray
{
static int[] get()
{
return new
int[]{10,30,50,90,60};
}
Multi-Dimensional Array
An array with two dimension in both horizontal and vertical is called single
dimensional array. We can access each element by it’s index which starts
from 0. It has double subscript([ ][ ]). data is stored in row and column
based index (also known as matrix form).
Syntax:
arr[0][0]=1; arr[0]
[1]=2; arr[0][2]=3;
arr[1][0]=4; arr[1]
[1]=5; arr[1][2]=6;
7
arr[2][0]=7; arr[2]
[1]=8; arr[2][2]=9;
class Testarray3
{
public static void main(String
args[])
{
int arr[][]={{1,2,3},{2,4,5},
{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
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.
Jagged Array, class name of java array, copying a java array, cloning
a java array