Wednesday 2 October 2013

How to Define and Use A Java Array

Java Arrays are data structures containing a fixed number of values objects of the same type. Each item in an array is called an element, and each element is accessed by its numerical index.

The following program creates an array of integer , putting values and prints each value of array in standard output.

public class techedifyOne {   
    public static void main(String[] args) {       
        int[] ary;// declares an array of integers
       
ary = new int[5];// allocates memory for 5 integers
       
ary[0] = 1;// initialize first element
       
ary[1] = 2;//and so on
       
ary[2] = 3;
       
ary[3] = 4;
       
ary[4] = 5;
        System.out.println("Element at index 0: "+
ary[0]);
        System.out.println("Element at index 1: "+
ary[1]);
        System.out.println("Element at index 2: "+
ary[2]);
        System.out.println("Element at index 3: "+
ary[3]);
        System.out.println("Element at index 4: "+
ary[4]);
    }


Output:
Element at index 0: 1
Element at index 1: 2
Element at index 2: 3
Element at index 3: 4
Element at index 4: 5


In above program declares a variable with following code :

int[] ary;

When you declare a Java array, you need to give it a data type. In above program , we declare an integer array containing five elements.see following code :

ary = new int[5];

An element of array will be access by index of that array. In above program , first element is initialize ny accessing element on 0 index. see following code :

ary[0] = 1;// initialize first element


we can also declare multidimensional  array by using two or more set of brackets.
e.g.
        String [][] val;
        val = new String[2][2];
        val[0][0]="value One";
        val[0][1]="value Two";
        val[1][0]="value Twenty One";
        val[1][1]="value Twenty Two";


we can also declare multidimensional  array with initialization of value.
e.g.
        String [][] val =
        {
            {"value One","Value Two"},
            {"value Twenty One","Value Twenty  Two"}
        };








No comments:

Post a Comment