Java Array declaration

This tutorial will help you how to declare array in java

Java Array declaration

This tutorial will help you how to declare array in java

Java Array declaration

Java Array declaration

In this section you will learn how to declare array in java. As we know an array is collection of single type or similar data type. When an array is created its length is determined. An array can hold fixed number of value and can be accessed by a square bracket called index.

Syntax : data-type[] array-name;

int[] arr ; (declares an array of integer type)

Like declaration of variable of other type, array is declared and it has two parts, one is type and other is array name. By type we mean the data type of element and index means that this variable holds an array. The index will hold the integer value that indicate the size of array. The array name can be anything as you want. While declaring an array is just to inform compiler that this variable will hold an array. Similarly like above declaration you can declare array of any type as follows:

String[] arr;
boolean[] arr;
float[] arr;
double[] arr;
char[] arr;

You can also put the square bracket after the array-name:

int arr[];

For allocating array to memory then declare the array with new keyword.

int[] a=new int[5];

These declaration indicate, it will allocate space in the memory with array size 5 which hold five element.

To declare two-dimensional array place two square bracket with type or array-name:

int[][] array-name;

These are two index indicating rows and column of array. It is called an array of array. 

 Example : Code to display the element  array :


public class ArrayDeclaton {
	public static void main(String args[])
	{
		int a[]={10,20,30,40,50};
		System.out.println("First element of array = "+a[0]);
		System.out.println("Second element of array = "+a[1]);
		System.out.println("Third element of array = "+a[2]);
		System.out.println("Fourth element of array = "+a[3]);
		System.out.println("Fifth element of array = "+a[4]);
	}
}

Output from this program is :