Single Dimension Array in Java programming Hands on coding

1-D Array in Java



  • This is a collection of data of similar data type.
  • It can be used to store the group of data simultaneously.
  • It stores the data of same type which means an integer array can store only integer values and ,character array stores only character value and so on.
  • We can fetch data from array using index values.
  • The index values of array always starts with 0.
  • Index value will be always an integer number.
  • Array may be of different data type such as int, char, float etc.

Syntax: 

  • Here 'a' is the name of array, int is the data type ,  and Size of array is 5 which 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