Menu
Topics Index
...
`


Array - Overview >
Siva Nookala - 11 Apr 2016
Unlike primitive data types, any array has to be created using the new operator. A reference to an array can be declared without any elements and can be assigned to null. A reference can be further modified as well.

To create an array, you first must create an array variable of the desired type. The general form of a one-dimensional array declaration is
type var-name[] = new type[desired-length];
  • type tells the element type e.g., int, float
  • var-name gives the variable name e.g., student_marks, months
  • new allocates memory required for the array with the size mentioned at desired-length e.g., 5, 12

The following code creates an array of student marks for a class with 25 students. And all elements in the array are initialized to zero automatically.
int student_marks[] = new int[25];
  • Arrays are allocated at run-time, hence we can use a variable to set their dimension.
int array_size = 100;
float[] my_array = new float[array_size]; // array_size should be of type byte, short or int
  • You can assign an array a null value but you can't create an empty array by using a blank index.
int[] array = null; // legal
int[] array = new int[]; // illegal initialization
  • The length of the array can be obtained using the length variable in array. This variable will be useful when iterating through the values of an array.
int[] array = new int[12];
System.out.println("Array length is " + array.length);
Accessing array elements explains about how to access the array elements i.e. how to assign values to elements of an array and how to read them.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.