Arrays in Java
Arrays in Java
Advantages
• Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
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.
1
Types of Array in java
• There are two types of array.
• dataType arr[];
• arrayRefVar=new datatype[size];
class Testarray{
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]);
}}
2
class Testarray1{
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
System.out.println(a[i]);
}}
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.
3
// Example to add values entered into array
import java .util.Scanner;
public class TakingInput
{
public static void main(String[] args) {
int sum = 0;
Scanner s=new Scanner(System.in);
System.out.println("enter number of elements");
int n=s.nextInt();
int arr[]=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++){
//for reading array
arr[i]=s.nextInt();
sum = sum + arr[i];
}
System.out.println("Sum:"+sum);
/*for(int i: arr)
{
//for printing array
System.out.println(i);
} */
}
}
• dataType []arrayRefVar[];
4
Example to instantiate Multidimensional Array in Java
• arr[0][0]=1;
• arr[0][1]=2;
• arr[0][2]=3;
• arr[1][0]=4;
• arr[1][1]=5;
• arr[1][2]=6;
• arr[2][0]=7;
• arr[2][1]=8;
• arr[2][2]=9;
• //Java Program to illustrate the use of multidimensional array
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();
}
}}