Single Dimensional Array in Java programming Hands on Coding

Array in Java;


  • Array is the collection of data of similar data type.
  • It can be used to store group of data simultaneously.
  • It can store data of similar kind of data type means an integer array can store only integer value ,character array can store only character value and so on.
  • We cannot fetch the data from array directly therefore we use index point.
  • The index value of array always start with 0.
  • Index value is always an integer.
  • Array may be of any data type such as int, char, float etc.


Syntax;

  • Here a is the name of array.
  • int is the data type of array.
  • Size of array is 5. It means we can store maximum 5 values in this array.


Initialization of array method 1:

 int ar[]={45,23,89,12,78};   

Initialization of array method 2:

 int a[]=new int[5];   
    a[0]=45;   
    a[1]=23;   
    a[2]=89;   
    a[3]=12;   
    a[4]=78;   


Printing of array element method 1:

 class Easy   
 {   
   public static void main(String[] args)   
   {   
     //array declaration   
     int ar[] = {10,50,80,40,60};   
     System.out.println("Value at ar[0]="+ar[0]);   
     System.out.println("Value at ar[1]="+ar[1]);   
     System.out.println("Value at ar[2]="+ar[2]);   
     System.out.println("Value at ar[3]="+ar[3]);   
     System.out.println("Value at ar[4]="+ar[4]);   
   }   
  } 
  
 / ### Output ###   
 Value at ar[0]=10   
 Value at ar[1]=50   
 Value at ar[2]=80   
 Value at ar[3]=40   
 Value at ar[4]=60 /   



Printing of array element method using loop:

 class Easy   
 {   
   public static void main(String[] args)   
   {   
     //array declaration   
     int ar[] = {10,50,80,40,60};   
     for(int i=0; i<=4; i++)   
     System.out.println("Value at ar["+i+"]="+ar[i]);   
   }   
 }   
 
 / ### Output ###   
 Value at ar[0]=10   
 Value at ar[1]=50   
 Value at ar[2]=80   
 Value at ar[3]=40   
 Value at ar[4]=60 /   




User Input in Array:

 import java.util.Scanner;   
 class Easy   
 {   
   public static void main(String[] args)   
   {   
    Scanner in=new Scanner(System.in);   //array declaration   
    int ar[]=new int[5];   
    int i;   
    for(i=0;i<=4;i++)   
     {   
      System.out.println("Enter element at "+(i+1));   
      ar[i]=in.nextInt();   
     }   
     for(i=0;i<=4;i++)   
     System.out.println("Value at ar["+i+"]="+ar[i]);   
   }   
  }   
  
 / ### Output ###   
 Enter element at 1= 15   
 Enter element at 2=25   
 Enter element at 3=53   
 Enter element at 4=10   
 Enter element at 5=95   
 Value at ar[0]=15   
 Value at ar[1]=25   
 Value at ar[2]=53   
 Value at ar[3]=10   
 Value at ar[4]=95 /   



Post a Comment

0 Comments