Arrays in Java

Java 8Object Oriented ProgrammingProgramming

You can create an array by using the new operator with the following syntax −

Syntax

arrayRefVar = new dataType[arraySize];

The above statement does two things −

  • It creates an array using new dataType[arraySize].

  • It assigns the reference to the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below − 

dataType[] arrayRefVar = new dataType[arraySize];

Alternatively, you can create arrays as follows − 

dataType[] arrayRefVar = {value0, value1, ..., valuek};

The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.

Example

Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList − 

double[] myList = new double[10];

The following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9.

raja
Published on 06-Feb-2018 13:32:50
Advertisements