0

I'm being asked to write a brief description on how to initialise and declare an array of different data types (string, int, double, etc) in Java. I thought initialising it would look something like this if it was of data type double:

double[] ArrayName = {13.5, 18.4, 19.6, 21.4};

OR

double[] ArrayName = new double[4];
ArrayName[0] = 13.5;
ArrayName[1] = 18.4;
ArrayName[2] = 19.6;
ArrayName[3] = 21.4;

So, if that is how you initialise an array, what would declaring an array look like?

2
  • 4
    You don't declare an array, you declare an array reference variable. You may (if you wish) then initialize that reference variable with an reference value generated via new or by using the literal array notation.
    – Hot Licks
    Jan 1, 2015 at 15:43
  • I just updated my answer. @Lucas806
    – Jobs
    Jan 1, 2015 at 16:22

3 Answers 3

4

Your first example will be compiled into second one.

So this code

double[] ArrayName = {13.5, 18.4, 19.6, 21.4};

contains

  1. variable declaration: double[] ArrayName
  2. array instantiation: new double[4]; (and assigning this array object to variable ArrayName)
  3. initialization of array with user's elements: ArrayName[0] = 13.5; ArrayName[1] = 18.4; ....
2

declaration -> double[] x

initialization -> x = new double[]{.....}

0

Initializing an array:

double[] ArrayName = {13.5, 18.4, 19.6, 21.4};

Declaring an array:

double[] ArrayName = new double[4];

You did both in your example. For more information please refer to the following:

http://www.cs.berkeley.edu/~jrs/61b/lec/06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.