Creating Arrays in Java

Chapter 4 - Creating and Using Arrays

    Creating Arrays in Java

  • Creating Arrays:

    Create an array by using the new operator with the following syntax:

    arrayRefVar = new dataType[arraySize];
    

    The above statement refer two things:

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

                   •  It assigns the reference of 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 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:

              The 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]; 

               myList holds ten double values and the indices are from 0 to 9.

© 2015 by Learncertification All Rights Reserved. The certification names are the trademarks of their respective owners. Terms & Privacy Policy