Arrays in Java
An array is a collection of similar type of elements which have a
contiguous memory location.
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.
Advantages & Disadvantages
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.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array. It doesn't
grow its size at runtime.
Types of Array in java
There are two types of array.
Single Dimensional Array
Multidimensional Array
Single Dimensional Array in Java
Syntax to Declare a Single Dimensional Array in Java
dataType []arr;
Example : int []arr;
OR
dataType arr[];
Example : int arr[];
Instantiation of an Array in Java
arrayReference Variable = new datatype[size];
Example : arr=new int[5];
Declaration and Instantiation together
int arr[]= new int[5];
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
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]);
}}
Output:
10
20
70
40
50
We can declare, instantiate and initialize the java
array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
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]);
}}
Output:
33
3
4
5
What happens if we try to access element
outside the array size?
JVM throws ArrayIndexOutOfBoundsException to
indicate that array has been accessed with an
illegal index. The index is either negative or greater
than or equal to size of array.
class Testarray{
public static void main(String args[]){
int a[]=new int[2];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
//traversing array
for(int i=0;i<=a.length;i++)
System.out.println(a[i]);
Runtime error
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 2 at
GFG.main(File.java:12)
Output
10
20
How to read values into an array using for loop
import java.util.*;
public class arr1
{
public static void main()
{ System.out.println("elements
of array a[]");
int a[]= new int[10];
for(i=0;i<10;i++)
int i;
{
Scanner sc=new
Scanner(System.in);
System.out.print(a[i]+"\t");
System.out.println("enter }
numbers"); }
for(i=0;i<10;i++) }
{
a[i]=sc.nextInt();
}