One-Dimensional Array in Java


☞Syntax to declare an Array in java

dataType[ ] arr; (or)
dataType [ ]arr; (or)
dataType arr[ ];

☞Instantiation of an Array in java

arr=new datatype[size];

☞Declaration and instantiation at the same time

datatype arr[]=new datatype[size];

Providing fixed values to an array

☞You can initialize like this.

int arr[]=new int[]{12,14,15,16,18};
int arr[]={12,14,15,16,18};

☞You cannot initialize like this.

int arr[]=new int[2]{2,4,5,6,8};
int arr[]=new int[5]{2,4,5,6,8};

Example

class ArrayExample1{
    public static void main(String args[]){

    	  //declaration and instantiation
    	  int a[]=new int[5];   
               
          //initialization
    	  a[0]=10;				 
    	  a[1]=87;  
    	  a[2]=76;  
    	  a[3]=98;  
    	  a[4]=56;  

    	  //printing an array
    	  for(int i=0;i<a.length;i++) 
    	       System.out.print(a[i]+" ");    

      }
}

Output

10 87 76 98 56

Example

class ArrayExample2{
    public static void main(String args[]){

          //declaration, instantiation and initialization
    	  int a[]={10,87,76,98,56};
	
    	  //printing an array
    	  for(int i=0;i<a.length;i++) 
    	       System.out.print(a[i]+" ");    

      }
}

Output

10 87 76 98 56

Example

class ArrayExample3{
    public static void main(String args[]){

          //declaration, instantiation and initialization
    	  int a[]=new int []{10,87,76,98,56}; 

    	  //printing an array
    	  for(int i=0;i<a.length;i++) 
    	       System.out.print(a[i]+" ");    

      }
}

Output

10 87 76 98 56

Taking values from the user

Example

import java.util.*;
class ArrayExample{        
  public static void main(String args[]){
    Scanner sc=new Scanner(System.in);

        System.out.println("Enter the size");
        int size=sc.nextInt();
        
        //declaration and instantiation
        int arr[]=new int[size];
        
        //Taking values through keyboard
        System.out.println("Enter numbers");
        for(int i=0;i<arr.length;i++)
            arr[i]=sc.nextInt();
        
        //Printing values of an array
        System.out.println("The numbers are");
        for(int i=0;i<arr.length;i++)
            System.out.println(arr[i]);
  }
}

Output

Enter the size
3
Enter numbers
78
67
45
The numbers are
78
67
45

Note :
1. length is the built-in property of an array, so we access it using the following syntax :
array_name.length
2. It gives the size of an array.