user3313947
user3313947

Reputation:

What's the difference between declaring and initialising an array in Java?

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?

Upvotes: 0

Views: 1691

Answers (3)

Jobs
Jobs

Reputation: 3377

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

Upvotes: 0

Pshemo
Pshemo

Reputation: 124275

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; ....

Upvotes: 4

bajky
bajky

Reputation: 342

declaration -> double[] x

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

Upvotes: 2

Related Questions