Java Program to Demonstrate the Use of Arrays

Arrays are very important concept in any programming language and java is not very different. An array is a sequential arrangement of variables of same type that share same name.

Instead of declaring lot of independent variables of same type, you can declare a sequential order of variables that can be manipulated using an index value.

This program is written using NetBean 8.2 installed on a Windows 7 64-bit system. It is intended for beginners of Java programming.

Problem Definition

There are many ways to declare an array in Java. This program demonstrate those declarations and assign values to the array and print the results.

All the declaration type shown here none of them are superior to each other, but different ways to work with arrays for solving computing problems.

Program Code

  
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package JavaExamples;

/**
*
* @author Admin
*/
public class ArrayDemo {

public static void main(String[] args){

int a[] = new int[5];
int b[] = {2,3,4,5};

int i;

a[0] = 10;
a[1] = 20;
a[2] = 30;
a[3] = 40;
a[4] = 50;

for(i = 0; i < 5;i++){

System.out.println("a["+i+"]=" +a[i]);
}

for(i =0 ; i < 4;i++){

System.out.println("b["+i+"]=" + b[i]);
}
}
}

Output – Array Demo

The output of the above program is given below.
 

  
a[0]=10
a[1]=20
a[2]=30
a[3]=40
a[4]=50
b[0]=2
b[1]=3
b[2]=4
b[3]=5
Advertisements