Java Arrays

An array is a one of the data structure in Java, that can store a fixed size sequential collection of elements of same data type.

Define an Array in Java

Syntax:
datatype[] identifier; //preferred way
or
datatype identifier[];
Example:
char[] refVar;
int[] refVar;
short[] refVar;
long[] refVar;
int[][] refVar; //two-dimensional array

Initialize an Array in Java

By using new operator array can be initialize.
int[] age = new int[5];    //5 is the size of array.
Arrays can be initialized at declaration time also:
int age[5]={22,25,30,32,35};
Initializing each element separately in loop:
Example:
public class Sample {

    public static void main(String args[]) {
        int[] newArray = new int[5];

        // Initializing elements of array seperately
        for (int n = 0; n < newArray.length; n++) {
            newArray[n] = n;
        }
    }
}

A pictorial representation of the array:

Java-One-Dimensional-array

Accessing Array Elements in Java

Example:
public class Sample {

    public static void main(String args[]) {
        int[] newArray = new int[5];

        // Initializing elements of array seperately
        for (int n = 0; n < newArray.length; n++) {
            newArray[n] = n;
        }
        System.out.println(newArray[2]); // Assigning 2nd element of array value
    }
}
Program Output:

java-array-in-loop



                                                                      ⏪ PREVIOUS PAGE          NEXT PAGE ⏩

No comments:

Post a Comment