Wednesday, 8 November 2017

Java Arrays

November 08, 2017 Posted by Prakash No comments
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.
For many large applications there may arise some situations that needs a single name to store multiple values. To process such large amount of data, programmers need powerful data types that would facilitate efficient contiguous bulk amount of storage facility, accessing and dealing with such data items. So, arrays are used in Java. In this tutorial you will learn about what arrays are and what the types are and how they are used within a Java program.

Define an Array in Java

The syntax of declaring array variables is:
Syntax:
datatype[] identifier; //preferred way
or
datatype identifier[];
The syntax used for instantiating arrays within a Java program is:
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.
Example:
int[] age = new int[5];    //5 is the size of array.
Arrays can be initialized at declaration time also.
Example:
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 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

0 comments:

Post a Comment