Data Structures

Arrays in Java

Array declaration:
To use an array in a program , we must declare a variable to reference the array and specify the type of array the variable can reference. Here is the syntax for declaring an array variable:
Syntax:

dataType[] arrayRefVar = new dataType[arraySize];
Or
dataType arrayRefVar[] = new dataType[arraySize]; 

Note: For convenience int[] num is preferable because it clearly tells that you are talking here about array For Example:

double[] arr = new double[5];
int[] arr = new int[5];

Initialization
The syntax for initialization is:

int[] arrayRefVar = {value, value, value, .., value};
Or
int[] arrayRefVar = new int[5]; arrayRefVar[0] = value; arrayRefVar[1] = value; arrayRefVar[2] = value; arrayRefVar[3] = value; arrayRefVar[4] = value;

For example:

int[] arr = {10, 20, 30, 40, 50};
or
arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50;

Array Size and Default Values
When space for an array is allocated, the array size must be given, to specify the number of elements that can be stored in it. The size of an array cannot be changed after the array is created. Size can obtained using arrayRefVar.length. For example, myList.length is 10.
When an array is created, its elements are assigned the default value of 0 for the numeric primitive data types, '\u0000' for char types,, and false for boolean types.

Array Indexed Variables
The array elements are accessed through the index. Array indices are 0 based; that is, they start from 0 to arrayRefVar.length-1.
Each element in the array is represented using the following syntax, known as an indexed variable:

arrayRefVar[index];

Some Simple Examples
1) A simple program to print an array.

class Example1
{  
    public static void main(String args[])
    {  
        // declaration, instantiation and initialization  
        int[] arr = {10, 20, 30, 40, 50};

        // printing array ( length is property of array )
        for (int i=0;i<arr.length;i++)
            System.out.print(arr[i]+ " ");  
    }
}

Output:

10 20 30 40 50 

2)A simple example to get minimum number in an array using a method.

class Example2
{  
    static void min(int myList[])
    {  
        int min = myList[0];  
        for (int i=1; i<myList.length; i++)  
            if (min > myList[i])  
                min = myList[i];  

            System.out.println(min);  
    }  

    public static void main(String args[])
    { 
       int arr[] = {20, 30, 10, 40, 50};      
       min(arr); //passing array to method  
    }
}

Output:

10


Recent Comments

Feedback

For any feedback,email us at feedback@geeksforgeeks.org

Report a Bug

For any report or bug,email us at support@geeksforgeeks.org